我正在制作Android应用,有一个初学者的问题:
有没有办法推迟Observables排放,直到2个订阅者订阅?因为我不希望第二个错过数据.
谢谢
解决方法:
是的,使用ConnectableObservable类型进行确定性多播支持此用例.
有两种方法可以使用它.
第一个也是最简单的是使用这样的发布重载:
Observable<Long> sourcetoShare = Observable.interval(10, TimeUnit.MILliSECONDS); // multiple subscriptions deterministically subscribed to using publish() sourcetoShare.publish(l -> { Observable<String> a = l.map(t -> "first subscriber " + t); Observable<String> b = l.buffer(4).map(t -> "second subscriber " + t); return Observable.merge(a, b); }).take(20).toBlocking().forEach(System.out::println);
或者,如果您需要在连接所有订户后手动控制源何时启动和停止,您可以直接使用ConnectableObservable,如下所示:
Observable<Long> sourcetoShare = Observable.interval(10, TimeUnit.MILliSECONDS); // multiple subscriptions deterministically subscribed to using ConnectableObservable ConnectableObservable<Long> published = sourcetoShare.publish(); Observable<String> a = published.map(t -> "first subscriber " + t); Observable<String> b = published.buffer(4).map(t -> "second subscriber " + t); Observable.merge(a, b).take(20).forEach(s -> System.out.println("published => " + s)); // Now that everything is wired up, connect the source published.connect(); // since we are connecting asynchronously and need to 'connect' after subscribing // we have to manually give it time to execute try { Thread.sleep(1000); } catch (InterruptedException e) { // Todo auto-generated catch block e.printstacktrace(); }
以下是文档的链接:
> http://reactivex.io/RxJava/javadoc/rx/Observable.html#publish(rx.functions.Func1)
> http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html
> http://reactivex.io/documentation/operators.html#connectable
以上是内存溢出为你收集整理的android – Rxjava,如何推迟排放,直到一些订阅者订阅?全部内容,希望文章能够帮你解决android – Rxjava,如何推迟排放,直到一些订阅者订阅?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)