-
-
Save jcmm33/3b1b3d0c4179b68044c02d4f1a65f629 to your computer and use it in GitHub Desktop.
async await reactive options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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