Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of Subject for RxJava's Single?

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.

like image 662
Robert Lewis Avatar asked Feb 01 '18 23:02

Robert Lewis


People also ask

What is RX subject?

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.

What is difference between single and Observable?

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.

How do you convert single to Observable?

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.

What is single in Rx Java?

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.


1 Answers

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().

like image 79
miensol Avatar answered Sep 21 '22 13:09

miensol