Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava How to subscribe a Subject to an Observable

The documentation says, that a Subject is a Observer and can subscribe to Observables, but I can't find a way to do it in code.

Thanks in advance!

like image 462
krzysiek Avatar asked Apr 21 '16 17:04

krzysiek


People also ask

Why is subject Observable?

A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. Every Subject is an Observable. Given a Subject, you can subscribe to it, providing an Observer, which will start receiving values normally.

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 onNext in RxJava?

onNext(): This method is called when a new item is emitted from the Observable. onError(): This method is called when an error occurs and the emission of data is not successfully completed. onComplete(): This method is called when the Observable has successfully completed emitting all items.


1 Answers

Sample junit code:

@Test
public void shouldSubscribeToSubjectToObservable() throws InterruptedException {
    Observable<Integer> observable = Observable.just(1, 2);
    PublishSubject<Object> subject = PublishSubject.create();
    subject.subscribe(o -> {
        System.out.println("o = " + o);
    });

    observable.subscribe(subject);

    Thread.sleep(1000);
}  
like image 199
Entea Avatar answered Oct 06 '22 16:10

Entea