How to use Rx to asynchronously query Twitter search?
I'm thinking about using Rx (Reactive Framework) in order to asynchrono开发者_JAVA技巧usly query Twitter search API on a given keyword. The sample app I'd like to build should be able to display new tweets in the console.
Do you think it is possible to do that ? Would it be simpler than using standard programming techniques ?
How would you do that ?
Thank ! Jeremy
A quick mockup of how it could be done. Note, I've only done a simple web request but this should easily extend to interact with the Twitter API.
Update: my previous sample didn't work well with repeating requests. The following improved sample uses Observable.Interval
to generate a continuous stream of ticks, driving the creation of requests and response download.
Observable
.Interval(TimeSpan.FromSeconds(5))
.Select(ticks => (HttpWebRequest)WebRequest.Create("http://demicode.com"))
.Select(request => Observable.FromAsyncPattern(request.BeginGetResponse,
asyncResult =>
{
using(var response = request.EndGetResponse(asyncResult))
using (var sr = new StreamReader(response.GetResponseStream()))
{
return DateTime.Now.ToString() + sr.ReadToEnd();
}
}))
.SelectMany(getContent => getContent())
.ObserveOnDispatcher()
.Subscribe(content => downloadContent.Text = content);
Update 2: Seems like using libraries like TweetSharp would handle the Twitter requests nicely for you. Observable.FromAsyncPattern
combined with the async twitter.BeginRequest
method makes a nice combination.
精彩评论