PublishSubject -有一种方法来执行onNext()



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()上做一些事情?

这样的装饰在实践中是行不通的。只要保持原始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");

相关内容

  • 没有找到相关文章

最新更新