无痕客

落花无情,流水无痕……

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
(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)

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
posted on 2010-04-18 11:09  无痕客  阅读(471)  评论(0编辑  收藏  举报