Single
is an observable that emits only a single item. The factory operators for Single
is more or less similar with observables restricted to a single emission. The only noticeable difference is the observer definition
public interface SingleObserver<T> {
void onSubscribe(@NonNull Disposable d);
void onSuccess(@NonNull T t);
void onError(@NonNull Throwable e);
}
|
Like Observable there are no more onNext() and onComplete().
Example
Single so=Single.create(new SingleOnSubscribe<String>() {
@Override
public void subscribe(SingleEmitter<String> se) throws Exception {
se.onSuccess("Success ");
//se.onError(new Throwable("Exception"));
}
});
so.subscribe(s->System.out.println(s));
|
While compile and run this will retrun the result as
if we need to perform a one time network request, we can create it using Single and users of this observable does not need to look at the implementation details to know what to expect from this observable
Example 2:
Single<String> testSingle = Single.just("Single Observable");
//Create an observer
Disposable disposable = testSingle
.delay(2, TimeUnit.SECONDS, Schedulers.io())
.subscribeWith(
new DisposableSingleObserver<String>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onSuccess(String value) {
System.out.println(value);
}
});
Thread.sleep(3000);
//start observing
disposable.dispose();
|
This will return output after 2 seconds
RxJava Tutorial
RxJava - Environment Setup
RxJava’s Characteristics
RxJava - How Observable works
RxJava - Single Observable
RxJava - MayBe Observable
RxJava - Completable Observable
RxJava - Using CompositeDisposable
RxJava - Creating Operators
RxJava - Transforming Operators
RxJava - Filtering Operators
RxJava - Combining Operators
RxJava - Utility Operators
RxJava - Conditional Operators
RxJava - Mathematical Operators
RxJava - Subjects
RxJava - PublishSubject
RxJava - BehaviorSubject
RxJava - AsyncSubject
RxJava - ReplaySubject
RxJava - Schedulers
RxJava - Trampoline Scheduler
RxJava - NewThread Scheduler
RxJava - Computation Scheduler
RxJava - IO Scheduler
RxJava - From Scheduler
RxJava - Buffering