Using Rx Framework for async calls using the void AsyncMethod(Action callback) pattern

前端 未结 3 1147
深忆病人
深忆病人 2020-12-20 00:26

I\'ve seen tons of examples on how to use the Observable.FromAsyncPattern() in the Rx Framework to simplify Async calls, but I\'m using an interface that doesn\'t use the st

3条回答
  •  失恋的感觉
    2020-12-20 01:04

    I like Observable.Create for this, but @dahlbyk answer is incorrect(misses completion and performs the action in the unsubscribe handler). Should be something like this:

        IObservable> FromListCallbackPattern(
            Action>> listGetter)
        {
            return Observable
                .Create>(observer =>
                {
                    var subscribed = true;
                    listGetter(list =>
                    {
                        if (!subscribed) return;
                        observer.OnNext(list);
                        observer.OnCompleted();
                    });
                    return () =>
                    {
                        subscribed = false;
                    };
                });
        }
    

    Also, since the originating API returns an entire list altogether, I don't see a reason to transform it to observable too early. Let the resulting observable return a list as well, and if a caller needs to flatten it, he can use .SelectMany

提交回复
热议问题