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()上做某事?
答案 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");