本文介绍了为什么/如何使用无连接发布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么/如何在没有ConnectRefCount调用的情况下使用.Publish()?它有什么作用?示例代码:

Why/how should I use .Publish() without a Connect or RefCount call following? What does it do? Example code:

var source = new Subject<int>();

var pairs = source.Publish(_source => _source
    .Skip(1)
    .Zip(_source, (newer, older) => (older, newer))
);

pairs.Subscribe(p => Console.WriteLine(p));

source.OnNext(1);
source.OnNext(2);
source.OnNext(3);
source.OnNext(4);

pairspairs2有何不同:

var pairs2 = source
    .Skip(1)
    .Zip(source, (newer, older) => (older, newer));

推荐答案

Publish<TSource, TResult>(Func<IObservable<TSource, IObservable<TResult>> selector)重载文献不多. Lee Campbell没有在 introtorx.com 中进行介绍.它不会返回IConnectableObservable,大多数人都将其与Publish相关联,因此它不需要或不支持ConnectRefCount调用.

The Publish<TSource, TResult>(Func<IObservable<TSource, IObservable<TResult>> selector) overload is poorly documented. Lee Campbell doesn't cover it in introtorx.com. It doesn't return an IConnectableObservable, which is what most people associate with Publish, and therefore doesn't require or support a Connect or RefCount call.

这种形式的Publish基本上是一种防御性编码形式,可以避免源中可能出现的副作用.它订阅源一次,然后可以通过传入的参数安全地多播"所有消息.如果您查看问题代码,则只会提及一次source,而只有两次提及_source. _source是安全多播的可观察对象,source是不安全的多播对象.

This form of Publish is basically a form of defensive coding, against possible side-effects in a source observable. It subscribes once to the source, then can safely 'multicast' all messages via the passed in parameter. If you look at the question code, there's only once mention of source, and two mentions of _source. _source here is the safely multicasted observable, source is the unsafe one.

在上面的示例中,源是简单的Subject,因此它并不是真正不安全的,因此Publish无效.但是,如果要使用以下内容替换source:

In the above example, the source is a simple Subject, so it's not really unsafe, and therefore Publish has no effect. However, if you were to replace source with this:

var source = Observable.Create<int>(o =>
{
    Console.WriteLine("Print me once");
    o.OnNext(1);
    o.OnNext(2);
    o.OnNext(3);
    o.OnNext(4);
    return System.Reactive.Disposables.Disposable.Empty;
});

...您会发现使用pairs(正确)打印了一次打印一次",而使用pairs2打印了两次.如果您的观察对象将您希望只发生一次而不是多次发生的东西包装起来,例如数据库查询,Web请求,网络调用,文件读取以及其他副作用代码,则这种影响具有相似的含义.

...you would find "Print me once" printed once with pairs (correct), and twice with pairs2. This effect has similar implications where your observable wraps things like DB queries, web requests, network calls, file reads, and other side-effecting code that you want to happen only once and not multiple times.

TL; DR::如果您有一个可观察的查询引用了一个可观察的对象两次,则最好将该可观察的对象包装在Publish调用中.

TL;DR: If you have an observable query that references an observable twice, it is best to wrap that observable in a Publish call.

这篇关于为什么/如何使用无连接发布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:03