Skip to content

Instantly share code, notes, and snippets.

@anaisbetts
Created January 15, 2011 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anaisbetts/780562 to your computer and use it in GitHub Desktop.
Save anaisbetts/780562 to your computer and use it in GitHub Desktop.
//
// Get the webpage and block till it finishes (aka make an async func
// into a sync func)
//
string contents = GetWebpageAsStringAsync("http://foo").First();
// ...or wire up a callback
GetWebpageAsStringAsync("http://foo").Subscribe(x => {
Console.WriteLine(x);
});
//
// Get all three pages concurrently and retrieve the results
// as they come in
//
string[] pages = new[] { "http://foo", "http://bar", "http://baz" };
IObservable<string> websiteContent = pages.AsObservable().SelectMany(GetWebpageAsStringAsync);
websiteContent.Subscribe(x => {
Console.WriteLine(x);
});
//
// How about we get fancy, and do a running word count of all the pages
// we've looked at.
//
IObservable<int> runningTotal = pages.AsObservable()
.SelectMany(GetWebpageAsStringAsync)
.Scan(0, (acc, x) => acc + x.Split(" ").Length)
runningTotal.Subscribe(x => Console.WriteLine("Words we've seen so far: {0}", x));
//
// Ok, now let's mash the two together to get a running *average* words
// per site
//
IObservable<double> average = Observable.Zip(
websiteContent.Count(),
runningTotal,
(siteCount, totalWords) => (double)totalWords / siteCount);
average.Subscribe(x => Console.WriteLine("Average Words per Site: {0}", x));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment