rx subscribeOn无法使用Subject?

时间:2016-10-07 20:33:36

标签: android multithreading system.reactive

这是代码:

Observable<Integer> observable = Observable.just(1, 2);
observable.doOnNext(i -> System.out.println("Emitting " + i + " on thread " + Thread.currentThread().getName()))
          .subscribeOn(Schedulers.computation())
          .doOnNext(i -> System.out.println("Emitting " + i + " after subscribeOn" + " on thread " + Thread.currentThread().getName()))
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(i -> System.out.println( "Receiving " + i + " on thread " + Thread.currentThread().getName()));

它给了我这个输出:

I/System.out: Emitting 1 on thread RxComputationScheduler-1
I/System.out: Emitting 1 after subscribeOn on thread RxComputationScheduler-1
I/System.out: Emitting 2 on thread RxComputationScheduler-1
I/System.out: Emitting 2 after subscribeOn on thread RxComputationScheduler-1
I/System.out: Receiving 1 on thread main
I/System.out: Receiving 2 on thread main
一切都好。

现在我想用Subject做同样的事情,我已经改变了代码如下:

PublishSubject<Integer> subject = PublishSubject.create();

subject.doOnNext(i -> System.out.println("Emitting " + i + " on thread " + Thread.currentThread().getName()))
       .subscribeOn(Schedulers.computation())
       .doOnNext(i -> System.out.println("Emitting " + i + " after subscribeOn" + " on thread " + Thread.currentThread().getName()))
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(i -> System.out.println( "Receiving " + i + " on thread " + Thread.currentThread().getName()));

subject.onNext(1);

在这种情况下,我没有输出。为什么这样?以及如何在给定的Scheduler中强制使用Subject发出流量?

1 个答案:

答案 0 :(得分:-1)

决定是:

PublishSubject<Integer> subject = PublishSubject.create();
subject
      **.observeOn(Schedulers.computation())**
      .doOnNext(i -> System.out.println("Emitting " + i + " on thread " + Thread.currentThread().getName()))                    
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(i -> System.out.println( "Receiving " + i + " on thread " + Thread.currentThread().getName()));

subject.onNext(1);

或者您可以从Schedulers.computation()线程

调用subject.onNext(1)