Reactive Extensions Subscribe calling await

前端 未结 2 1048
逝去的感伤
逝去的感伤 2021-02-13 10:08

I want to perform an async call based for each event raised by a Reactive Extensions Observable. I\'m also trying to keep everything synchronized as I want the async ca

相关标签:
2条回答
  • 2021-02-13 10:41

    How about:

    settingsChangedInMemory
        .SelectMany(async _ => await SaveSettings(Extract()))
        .Subscribe(x => Apply(x));
    

    Never put an async in a Subscribe, you always want to put it in a SelectMany instead.

    0 讨论(0)
  • 2021-02-13 10:45

    You can use the new ForEachAsync method released in Reactive Extensions (Rx) 2.0 like so:

    await observable
        .ForEachAsync(async x =>
        {
            Console.WriteLine(x);
            await Task.Delay(1000);
        });
    

    ForEachAsync returns a Task<T> which completes when the observable completes. More information in my blog post here or this blog post by the reactive extensions team.

    0 讨论(0)
提交回复
热议问题