RxJava2发布 [英] RxJava2 Publish

查看:98
本文介绍了RxJava2发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别

ObservableTransformer {
    Observable.merge(
        it.ofType(x).compose(transformerherex),
        it.ofType(y).compose(transformerherey)
    )
}

ObservableTransformer {
    it.publish{ shared ->
        Observable.merge(
            shared.ofType(x).compose(transformerherex),
            shared.ofType(y).compose(transformerherey)
        )
    }
}

当我使用这两个代码运行代码时,我得到了相同的结果.此处发布的内容是什么.

when I run my code using this two, I got the same results. What does publish do here.

推荐答案

区别在于,顶级转换器将对上游进行两次订阅,以便从下游进行一次订阅,从而复制了通常不需要的上游任何副作用:

The difference is that the top transformer will subscribe to the upstream twice for a single subscription from the downstream, duplicating any side effects of the upstream which is usually not wanted:

Observable<Object> mixedSource = Observable.<Object>just("a", 1, "b", 2, "c", 3)
      .doOnSubscribe(s -> System.out.println("Subscribed!"));


mixedSource.compose(f ->
   Observable.merge(
      f.ofType(Integer.class).compose(g -> g.map(v -> v + 1)),
      f.ofType(String.class).compose(g -> g.map(v -> v.toUpperCase()))
   )
)
.subscribe(System.out::println);

将打印

Subscribed!
2
3
4
Subscribed!
A
B
C

此处表示的副作用是打印输出Subscribed!取决于实际源中的实际工作,这可能意味着发送两次电子邮件,两次检索表的行.在这个特定的示例中,您可以看到,即使源值在其类型中交织在一起,输出也会单独包含它们.

The side-effect represented here is the printout Subscribed! Depending on the actual work in a real source, that could mean sending an email twice, retrieving the rows of a table twice. With this particular example, you can see that even if the source values are interleaved in their type, the output contains them separately.

相反,publish(Function)将为每个最终订户建立一个对源的订阅,因此源上的任何副作用都只会发生一次.

In contrast, publish(Function) will establish one subscription to the source per one end subscriber, thus any side-effects at the source only happen once.

mixedSource.publish(f ->
   Observable.merge(
      f.ofType(Integer.class).compose(g -> g.map(v -> v + 1)),
      f.ofType(String.class).compose(g -> g.map(v -> v.toUpperCase()))
   )
)
.subscribe(System.out::println);

可打印

Subscribed!
A
2
B
3
C
4

因为订阅源一次,并且每个项目都被多播到.ofType().compose()的两个分支".

because the source is subscribed once and each item is multicast to the two "arms" of the .ofType().compose().

这篇关于RxJava2发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆