PublishSubject - 有没有办法在onNext()上执行某些操作?

时间:2016-10-17 11:31:57

标签: java rx-java reactive-programming rx-android

PublishSubject非常适合在观察者和观察者之间建立桥梁:

    Observable<String> observable = Observable.just("string");

    PublishSubject<String> observer1 = PublishSubject.<String>create();

    Observer<Object> observer2 = new Observer<Object>() {...}

    // observer2 will receive all onNext and onCompleted events from observer1
    observer1.subscribe(observer2);

    //observer1 will get items from observable and propagate them to observer2
    observable.subscribe(observer1);

然而,它缺乏一种功能,可以做一些不能成为桥梁的东西,我的意思是能够做出类似的事情会派上用场:

PublishSubject<String> observer1 = PublishSubject.<String>create()
    .doOnNext( item ->  System.out.println("Do something with the item " + item) );

但是编译器投诉:Type mismatch: cannot convert from Observable<String> to PublishSubject<String>

有没有办法装饰PublishSubject在next()上做某事?

1 个答案:

答案 0 :(得分:3)

这种装饰在实践中并没有真正起作用。只需保留对原始PublishSubject的引用,然后分发Observable doOnNext次返回。

PublishSubject<String> subject = PublishSubject.<String>create()

Observable<String> source = subject
   .doOnNext( item ->  System.out.println("Do something with the item " + item) );

source.subscribe(System.out::println, Throwable::printStackTrace);

subject.onNext("1");