mtyson mtyson - 1 month ago 25
Java Question

RxJava: Dynamic set of observables

I have a central class, call it

Central
. It can have 1-N observables added to it. These I need to add dynamically, and then know when the final onComplete() has executed.

How to do this?

Code sample:

public class Central {
public void addObservable(Observable o){
// Add the new observable to subscriptions
}
}

Answer

Use a PublishSubject:

PublishSubject<Observable<T>> subject = 
    PublishSubject.create();
subject.concatMap(o -> 
      o.doOnCompleted(() -> System.out.println("inner completed")))
    .doOnNext(System.out::println)
    .doOnCompleted(() -> System.out.println("completed"))
    .subscribe(subscriber);

subject.onNext(Observable.just(t1));
subject.onNext(Observable.just(t2, t3));
subject.onCompleted();

  .