In RxJava is there anything equivalent to the Subject
class that works for a Single
? Presumably I'd call its onSuccess( item )
or onError( Throwable )
methods and the output would be forwarded to the SingleSubscriber
.
I guess I could use an Observable
Subject
and transform it to a Single
but that seems a bit clunky.
Currently using RxJava 1 but interested in the situation with RxJava 2 also.
An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.
Observable: emit a stream elements (endlessly) Flowable: emit a stream of elements (endlessly, with backpressure) Single: emits exactly one element. Maybe: emits zero or one elements.
If I understood correctly, you want to convert Single<List<Item>> into stream of Item2 objects, and be able to work with them sequentially. In this case, you need to transform list into observable that sequentially emits items using . toObservable(). flatMap(...) to change the type of the observable.
Single. Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response. Sample Implementation: The below code always emits a Single user object.
In RxJava 2 there is SingleSubject
that you can use as follows:
SingleSubject<Integer> subject1 = SingleSubject.create();
TestObserver<Integer> to1 = subject1.test();
// SingleSubjects are empty by default
to1.assertEmpty();
subject1.onSuccess(1);
// onSuccess is a terminal event with SingleSubjects
// TestObserver converts onSuccess into onNext + onComplete
to1.assertResult(1);
TestObserver<Integer> to2 = subject1.test();
// late Observers receive the terminal signal (onSuccess) too
to2.assertResult(1);
Unfortunately there is no equivalent available in RxJava 1. However, as you have mentioned, you can achieve the desired result by calling subject.toSingle()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With