Skip to content

Instantly share code, notes, and snippets.

@jcmm33

jcmm33/Simple.cs Secret

Created March 26, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jcmm33/3b1b3d0c4179b68044c02d4f1a65f629 to your computer and use it in GitHub Desktop.
Save jcmm33/3b1b3d0c4179b68044c02d4f1a65f629 to your computer and use it in GitHub Desktop.
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