locked
Multiple Async calls and Reactive Extensions RRS feed

  • Question

  • Hi ,

    I make this async webrequest call mutliple times(can be twice or thrice depending on conditions)

               var request = HttpWebRequest.CreateHttp(url);

                var observableRequest = Observable.
                    FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.
                                                      EndGetResponse);
                Observable.Timeout(observableRequest.Invoke(), TimeSpan.FromSeconds(120)).
                    Subscribe(response => { HandleListResult(response); },
                    exception => { HandleListResultTimeOut(exception); });

    I have a Collection (List<string>)  in the ViewModel and i would like to keep adding to the collection after each response returns.

    What is the best practise to make this happen ? Would be great if someone can show me some sample code !

     

    Thanks in advance

     

    Thursday, February 24, 2011 11:43 PM

All replies

  • I think you are on the right path.

    Though I like using the observer for achieving the same behavior. You can cause little separation of concerns through it.

        public class UrlRequestHelper
        {
            public static void ProcessUrl(IObserver<WebResponse> observer, string url)
            {
                if (observer == null || string.IsNullOrWhiteSpace(url) )
                    return;

                var request = HttpWebRequest.CreateHttp(url);
                var observableRequest = Observable.
                    FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.
                                                      EndGetResponse);

                Observable.Timeout(observableRequest.Invoke(), TimeSpan.FromSeconds(120)).
                    Subscribe(observer);
            }
        }

    And in ViewModel, based on some trigger you can do:

                string url = "Url1";
                IObserver<WebResponse> responseObserver = Observer.Create<WebResponse>(
                    res => { HandleListResult(res); },
                    ex => { HandleException(ex); },
                    () => { /* Log, that the request has been completed and do some post completion action */ });
    
                UrlRequestHelper.ProcessUrl(responseObserver, url);
    




     

    Saturday, February 26, 2011 6:30 AM