Subscribe and immediately unsubscribe after first action

吃可爱长大的小学妹 提交于 2021-01-27 03:57:46

问题


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.

This is the approach I came up with:

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();
        });
    }
}

Example usage:

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();
    }
}

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?


回答1:


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 automatically disposes of the subscription after the nth element yields. :)

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.

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



来源:https://stackoverflow.com/questions/22786712/subscribe-and-immediately-unsubscribe-after-first-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!