(not yet) 101 Rx Samples
You!
Yes, you, the one who is still scratching their head trying to figure out this Rx thing.
As you learn and explore, please feel free add your own samples here, or tweak existing ones!
Anyone can (and should!) edit this page. (edit button is at the bottom right of each page)
Table of Contents
|
Asynchronous Background Operations
Start - Run Code Asynchronously
var o = Observable.Start(() => { Console.WriteLine("Calculating..."); Thread.Sleep(3000); Console.WriteLine("Done."); });
o.First(); // subscribe and wait for completion of background operation
Run a method asynchronously on demand
Execute a long-running method asynchronously. The method does not start running until there is a subscriber. The method is started every time the observable is created and subscribed, so there could be more than one running at once.
// Synchronous operation
public DataType DoLongRunningOperation(string param)
{
...
}
public IObservable<DataType> LongRunningOperationAsync(string param)
{
return Observable.CreateWithDisposable<DataType>(
o => Observable.ToAsync(DoLongRunningOperation)(param).Subscribe(o)
);
}
ForkJoin - Parallel Execution
var o = Observable.ForkJoin(
Observable.Start(() => { Console.WriteLine("Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return "Result A"; }),
Observable.Start(() => { Console.WriteLine("Executing 2nd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return "Result B"; }),
Observable.Start(() => { Console.WriteLine("Executing 3rd on Thread: {0}", Thread.CurrentThread.ManagedThreadId); return "Result C"; })
).Finally(() => Console.WriteLine("Done!"));
foreach (string r in o.First())
Console.WriteLine(r);
Result
Executing 1st on Thread: 3
Executing 2nd on Thread: 4
Executing 3rd on Thread: 3
Done!
Result A
Result B
Result C
摘自:http://rxwiki.wikidot.com/101samples