.PublishLast() 的用例(以前是 Prune) [英] Use case for .PublishLast() (previously Prune)

查看:30
本文介绍了.PublishLast() 的用例(以前是 Prune)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我对 RX 函数有很好的感觉"——我使用了其中的许多函数,或者可以想象其他函数是如何有用的——但我找不到 .Prune 函数的位置.我知道这是到 AsyncSubject 的多播,但这在实际场景中如何有用?

In my opinion, I have a pretty good "feel" for RX functions - I use many of them or can imagine how other can be useful - but I can't find a place for the .Prune function. I know that this is a Multicast to AsyncSubject, but how this can be useful in a real scenario?

Richard 说 WebRequest 是 Prune() 的一个很好的候选者.我仍然不明白如何.让我们举个例子 - 我想将传入的 uri 转换为图像:

Richard says WebRequest is a good candidate for Prune(). I still don't see how. Let's take an example - I want to transform incoming uri's to images:

    public static IObservable<BitmapImage> ToImage(this IObservable<string> source)
    {
        var streams = 
            from wc in source.Select(WebRequest.Create)
            from s in Observable
                .FromAsyncPattern<WebResponse>(wc.BeginGetResponse, 
                    wc.EndGetResponse)()
                .Catch(Observable.Empty<WebResponse>())
            select s.GetResponseStream();
        return streams
            .ObserveOnDispatcher()
            .Select(x =>
                        {
                            var bmp = new BitmapImage();
                            bmp.SetSource(x);
                            return bmp;
                        });
    }

我认为没有必要将 .Prune 附加到 .FromAsyncPattern,因为当您调用 FromAsyncPattern()(这很热门)时,您会立即"订阅.

I don't see it necessary to append .Prune to .FromAsyncPattern, because when you're calling FromAsyncPattern() (which is hot) you subscribe "instantly".

推荐答案

As it 在 RX 论坛上得到确认 Prune 只是一个便利运营商.

As it was confirmed on the RX Forum Prune is just a covenience operator.

如果您的 observable 有一个值并且您要发布它,可以用对 .Prune() 的单个调用替换 Publish\Connect

If your observable has a single value and you're publishing it, can replace Publish\Connect with a single call to .Prune()

所以根据我的经验,Prune 最常见的场景是:

So from my experience, the most common scenario for Prune is:

  • 你有一个冷 observable,它会产生副作用并且只发出一个值
  • 该 observable 的订阅者不止一个,所以你想让它变得热门(因为副作用)

论坛中指出的另一个问题是,当您需要在热可观察对象上缓存特定值时(通常是第一个).然后你使用 FromEvent(...).Take(1).Prune() 并且任何订阅它的人都将获得相同的值保证.这不仅仅是方便",而且几乎是实现结果的唯一简单方法.

Another, pointed out in the forum, is when you need to cache a particular value on a hot observable(usually first). Then you use FromEvent(...).Take(1).Prune() and anybody who subscribes to this will get the same value guaranteed. This one is not just "convenience", but pretty much the only easy way to achieve the result.

毕竟非常有用!

这篇关于.PublishLast() 的用例(以前是 Prune)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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