gpt4 book ai didi

java - PublishSubject - 有没有办法执行 onNext()?

转载 作者:行者123 更新时间:2023-11-29 04:38:53 24 4
gpt4 key购买 nike

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 的引用,并分发 doOnNext 返回的 Observable

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com