美文网首页RxJava
Rxjava Creating Observables -Def

Rxjava Creating Observables -Def

作者: shiyuzhe | 来源:发表于2018-12-12 18:55 被阅读6次

    Defer — do not create the Observable until the observer subscribes, and create a fresh Observable for each observer

    The Defer operator waits until an observer subscribes to it, and then it generates an Observable, typically with an Observable factory function. It does this afresh for each subscriber, so although each subscriber may think it is subscribing to the same Observable, in fact each subscriber gets its own individual sequence.

    In some circumstances, waiting until the last minute (that is, until subscription time) to generate the Observable can ensure that this Observable contains the freshest data.

    上文是官网介绍,附上连接:ReactiveX;里边有两个点:

    1.直到订阅时生成Observable,可以确保此Observable包含最新的数据。

    2.为每个接收者生成一个Observable,虽然不同接收者订阅了相同的Observable,但实际上每个接收者都有自己单独的序列。


    代码是来验证这两部分的:

    关于订阅时生成Observable,对比第20行和30行和下图的log,observable在开始发送事件时会打印“observable be subscribe”

    在页面创建时会先输出“range111","range112"。点击defer按钮时触发点击事件,订阅第20行生成的observable。

    关于每个接收者都有单独的序列,第一个接收者在subscribe时接收了返回值disposable(33行),第二个接收者的事件序列在新的线程中做了一个变换工作,这里调用第一个接收者的disposable.dispose()。

    还有我是在新的线程中做的事件发送,这样两个接收者的事件在不同的线程中发送。如果两个observable在同一个线程中发送数据是会顺序执行的,这样调用disposable.dispose()时第一个接收者已经接受完数据了。

    代码很简单就不贴了,欢迎指正,谢谢。

    code log

    相关文章

      网友评论

        本文标题:Rxjava Creating Observables -Def

        本文链接:https://www.haomeiwen.com/subject/jtvphqtx.html