Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Extensions Subscribe calling await

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 call to finish before the next event is handled.

How would one go about doing something similar to the following? I say similar as the code below does not compile.

settingsChangedInMemory
    .Subscribe(async _ => {
        var settings = Extract();
        await SaveSettings(settings);
    });

I'm not sure if it changes anything, but I would need to Subscribe to multiple Observables. For example another subscription like this.

settingsChangedOnDisk
    .Subscribe(async _ => {
        var settings = await ReadSettings(settings);
        Apply(settings);
    });

How would you use Reactive Extensions to do this?

like image 514
Daniel Little Avatar asked Jul 19 '14 17:07

Daniel Little


1 Answers

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.

like image 97
Ana Betts Avatar answered Sep 18 '22 14:09

Ana Betts