本文介绍了`share()`和`publish()。refCount()`之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

observable.publish()。refCount() observable.share()之间的实际区别是什么?什么是我们不想使用分享的情况的例子?

What's the practical difference between observable.publish().refCount() and observable.share(). What would be an example of an scenario in which we don't want to use share?

推荐答案

没有实际区别,如果你看一下'observable.prototype.share',你会看到它只返回'source.publish()。refCount()'。

There is no practical difference, if you look at 'observable.prototype.share' you will see that it simply returns 'source.publish().refCount()'.

至于你想要使用它的原因,更多的问题是当你的源开始广播时你需要多少控制权。

As to why you would want to use it, it is more a question of how much control you need over when your source starts broadcasting.

由于 refCount()将在第一次订阅时附加基础observable,很可能是后续的情况观察者会在他们订阅之前错过收到的消息。

Since refCount() will attach the underlying observable on first subscription, it could very well be the case that subsequent observers will miss messages that come in before they can subscribe.

例如:

var source = Rx.Observable.range(0, 5).share();

var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));

只有第一个订阅者才会收到任何值,如果我们想要收到它们,我们会使用:

Only the first subscriber will receive any values, if we want both to receive them we would use:

var source = Rx.Observable.range(0, 5).publish();

var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));

source.connect();

这篇关于`share()`和`publish()。refCount()`之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-02 22:18