RxJava:动态的可观察对象集

时间:2016-10-09 01:01:10

标签: java rx-java

我有一个中心课,称之为Central。它可以添加1-N个可观察量。这些我需要动态添加,然后知道最后的onComplete()何时执行。

怎么做?

代码示例:

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

更新

我已经在这一段时间里四处走动了。使用@ DaveMoten的回答,我已经接近了。

这是我的方法,可以随意添加一个新的observable,并在所有这些都已完成时得到通知(伪代码):

class central {
  PublishSubject<Observable<T>> subject = PublishSubject.create();
  int commandCount = 0;
  int concatCount = 0;
  addObservable(Observable newObs){
    commandCount++;
    concatCount++;
    subject.concatMap(o -> 
          o.doOnCompleted(
                  () -> { 
                    concatCount--;
                    LOG.warn("inner completed, concatCount: " + concatCount);
                  })
          ).doOnNext(System.out::println)
            .doOnCompleted(() -> { 
                System.out.println("OUTER completed");
            } ) .subscribe();

    onNext(newObs);
    subject.onCompleted(); // If this is here, it ends prematurely (after first onComplete)
    // if its not, OUTER onComplete never happens

    newObs.subscribe((e) ->{},
    (error) -> {},
    () -> {
        commandCount--;
        LOG.warn("inner end: commandCount: " + commandCount);
    });
  }
}
// ... somewhere else in the app:
Observable ob1 = Observable.just(t1);
addObservable.addObservable(ob1);
// ... and possibly somewhere else:
Observable ob2 = Observable.just(t2, t3);
addObservable(ob2);

// Now, possibly somewhere else:
ob1.onNext(1);
// Another place:
ob2.onNext(2);

日志记录如下:

19:51:16.248 [main] WARN  execute: commandCount: 1
19:51:17.340 [main] WARN  execute: commandCount: 2
19:51:23.290 [main] WARN  execute: commandCount: 3
9:51:26.969 [main] WARN   inner completed, concatCount: 2
19:51:27.004 [main] WARN  inner end: commandCount: 2
19:51:27.008 [main] WARN  inner completed, concatCount: 1
19:51:27.009 [main] WARN  inner end: commandCount: 1
19:51:51.745 [ProcessIoCompletion0] WARN  inner completed, concatCount: 0
19:51:51.750 [ProcessIoCompletion0] WARN  inner completed, concatCount: -1
19:51:51.751 [ProcessIoCompletion0] WARN  inner end: commandCount: 0
19:51:51.752 [ProcessIoCompletion0] WARN  inner completed, concatCount: -2
19:51:51.753 [ProcessIoCompletion0] WARN  inner completed, concatCount: -3

更新:我添加了一些计数器,证明我不了解concatMap正在发生的事情。你可以看到观察者本身的lambda订阅正确地倒数到0,但是concatMap oncomplete下降到-3!并且OUTER完成永远不会发生。

1 个答案:

答案 0 :(得分:2)

使用PublishSubject

PublishSubject<Observable<T>> subject = 
    PublishSubject.create();
subject
    // protect against concurrent calls to subject (optional)
    .serialize()
    .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();

  .