Created
January 15, 2011 00:32
-
-
Save anaisbetts/780562 to your computer and use it in GitHub Desktop.
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
// | |
// 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