With Rx, how do I ignore all-except-the-latest value when my Subscribe method is running

后端 未结 9 1581
暖寄归人
暖寄归人 2020-11-29 03:47

Using Reactive Extensions, I want to ignore messages coming from my event stream that occur while my Subscribe method is running. I.e. it sometimes takes me lon

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 03:58

    I've written a blog post about this with a solution that uses CAS instead of locks and avoids recursion. The code is below, but you can find a complete explanation here: http://www.zerobugbuild.com/?p=192

    public static IObservable ObserveLatestOn(
        this IObservable source,
        IScheduler scheduler)
    {
        return Observable.Create(observer =>
        {
            Notification pendingNotification = null;
            var cancelable = new MultipleAssignmentDisposable();
    
            var sourceSubscription = source.Materialize()
                .Subscribe(notification =>
                {
                    var previousNotification = Interlocked.Exchange(
                        ref pendingNotification, notification);
    
                    if (previousNotification != null) return;
    
                    cancelable.Disposable = scheduler.Schedule(() =>
                        {
                            var notificationToSend = Interlocked.Exchange(
                                ref pendingNotification, null);
                            notificationToSend.Accept(observer);
                        });
                });
                return new CompositeDisposable(sourceSubscription, cancelable);
        });
    }
    

提交回复
热议问题