Skip to content

Instantly share code, notes, and snippets.

@jcmm33 jcmm33/Simple.cs Secret
Created Mar 26, 2018

Embed
What would you like to do?
async await reactive options
class Program
{
static void Main(string[] args)
{
var inputs = new[] {1,2,3};
// ensures next task isn't executed until prior is completed - which is the implication with
// subscribe based async code
inputs.ToObservable().
Select((i) => Observable.Defer(() => LongishTask(i).ToObservable())).
Concat().
Subscribe(_ => { }, (e) => Console.WriteLine($" Exception {e.Message}"));
Console.ReadLine();
// will run more than one task at once, but error will be surfaced correctly
inputs.ToObservable().
SelectMany( async (i) => await LongishTask(i)).
Subscribe(_ => { }, (e) => Console.WriteLine($" Exception {e.Message}"));
Console.ReadLine();
// execution will take place concurrently for each task, but exception when raised
// won't surface in the pipeline, but rather take down the program instead
inputs.ToObservable().
Subscribe(async v => await LongishTask(v), (e) => Console.WriteLine($" Exception {e.Message}"));
Console.ReadLine();
}
static async Task<bool> LongishTask(int index)
{
Console.WriteLine($"I've started {index}");
// adjust to get even items to take less time than odd ones
await Task.Delay((index & 1) == 0 ? 250: 1000);
// just throw an exception and see what happens
if (index == 3)
{
throw new ArgumentException("");
}
Console.WriteLine($"I've finished {index}");
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.