订阅并在执行第一项操作后立即退订 [英] Subscribe and immediately unsubscribe after first action

查看:69
本文介绍了订阅并在执行第一项操作后立即退订的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 IObservable< T> 上进行订阅,并在收到类型为 T 的第一个元素后立即取消订阅(退订)(即,取消订阅)订阅后对第一个元素的操作.

I want to subscribe on an IObservable<T> and unsubscribe (dipose) the subscription right after receiving the first element of type T, i.e. I only want to call the action on the very first element I get after subscribing.

这是我想出的方法:

public static class Extensions
{
    public static void SubscribeOnce<T>(this IObservable<T> observable, Action<T> action)
    {
        IDisposable subscription = null;
        subscription = observable.Subscribe(t =>
        {
            action(t);
            subscription.Dispose();
        });
    }
}

示例用法:

public class Program
{
    public static void Main()
    {
        var subject = new Subject<int>();

        subject.OnNext(0);
        subject.OnNext(1);
        subject.SubscribeOnce(i => Console.WriteLine(i));
        subject.OnNext(2);
        subject.OnNext(3);

        Console.ReadLine();
    }
}

它按预期方式工作,仅打印 2 .这有什么问题还是要考虑的其他问题?也许可以使用RX随附的扩展方法更干净的方法吗?

It works as expected and only prints 2. Is there anything wrong with this or anything else to consider? Is there a cleaner way using the extension methos that come with RX out of the box maybe?

推荐答案

var source = new Subject();

source
  .Take(1)
  .Subscribe(Console.WriteLine);

source.OnNext(5);
source.OnNext(6);
source.OnError(new Exception("oops!"));
source.OnNext(7);
source.OnNext(8);

// Output is "5". Subscription is auto-disposed. Error is ignored.

Take nth 元素产生后自动处理预订.:)

Take automatically disposes of the subscription after the nth element yields. :)

就其他需要考虑的方面而言,对于您的自定义可观察对象,您应注意,您可能还希望将OnError和OnCompleted通知传递给您的观察者,Take也会为您处理.

As far as other things to consider, for your custom observable, you should note that you may also want to pass OnError and OnCompleted notifications to your observer, which Take also handles for you.

内置运算符还具有其他优点,例如更好的 Dispose 处理.

The built-in operators have other benefits as well, such as better Dispose handling.

这篇关于订阅并在执行第一项操作后立即退订的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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