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");

关于java - PublishSubject-是否可以执行onNext()方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40085274/

10-10 20:18