Reputation: 3252
As I am learning the Rx (Reactive extensions), I want to know the different between given 2 peice of code:
Code 1
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher(@"C:\Logs", "*.*");
watcher.EnableRaisingEvents = true;
var source = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(handler =>
{
FileSystemEventHandler fsHandler = (sender, e) =>
{
handler(e);
};
return fsHandler;
},
fsHandler => watcher.Created += fsHandler,
fsHandler => watcher.Created -= fsHandler
);
source.Subscribe(x => Console.WriteLine(x.Name + "is created"));
Console.Read();
}
Code 2
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher(@"C:\Logs", "*.*");
watcher.EnableRaisingEvents = true;
watcher.Created += watcher_Created;
Console.Read();
}
static void watcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name.ToString());
}
What is the different between above 2 peice of code as it produce the same result?
Even I gone through the core part and found that both the code line execute on saparate thread, then what is the difference between these and why I use Rx in such scenarios??
Thanks in advance!
Upvotes: 1
Views: 222
Reputation: 16894
In this specific example, there are two potential benefits to using Rx (emphasis on potential):
A convenient way to "unwire" the event handler: calling Dispose
on the subscription (the thing returned by the Subscribe
call) will have the same effect as watcher.Created -= handler
A way to compose events coming from this source with other IObservable
(and IEnumerable
, for that matter) sources. For example, if your use case is "I need to know when a file is created, then written to three times, etc, etc", you can create multiple IObservable
"watchers" from the various events exposed on the FileSystemWatcher
, then create a query that will fire only when the correct conditions occur
in pseudo-LINQ:
var createEvents = <get created event handler>;
var changeEvents = <get changed event handler>;
var createThenChangeThenChangeThenChange =
from create in createEvents
where create.Name == "some file I care about"
from firstChange in changeEvents
from secondChange in changeEvents
from thirdChange in changeEvents
select new { create, firstChange, secondChange, thirdChange};
Upvotes: 1