Reactive Extensions UI Update

I make this asynchronous web request call several times (maybe twice or thrice or even 6 times 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) in the ViewModel that has a LisBox binding, and I would like to continue adding to the collection after each answer.

What is the best practice for this using Reactive Extensions? It would be great if someone could show me some sample code!

Thanks in advance

+3
source share
2 answers

You can translate a stream of URLs directly into streams:

    public static IObservable<Stream> RequestToStream(
        this IObservable<string> source, TimeSpan timeout)
    {
        return
            from wc in source.Select(WebRequest.Create)
            from s in Observable
                .FromAsyncPattern<WebResponse>(wc.BeginGetResponse,
                    wc.EndGetResponse)()
                .Timeout(timeout, Observable.Empty<WebResponse>())
                .Catch(Observable.Empty<WebResponse>())
            select s.GetResponseStream();
    }

And then you need to watch your answers in the user interface, you need to use .ObserveOnDispatcher (), fe:

        Observable
            .Return("www.msdn.com")
            .RequestToStream(TimeSpan.FromSeconds(1))
            .ObserveOnDispatcher()
            .Subscribe(request => UpdateUI(Request));
+2
source

ReactiveUI CreateCollection()

IObservable<string> source; // Maybe this is a Subject<string> or whatever

myBoundCollection = source
    .SelectMany(webServiceCall) // This is your FromAsyncPattern func
    .CreateCollection();  // Pipe the Observable to a Collection

ReactiveUI ObserveOn, , .. , .

+2

Source: https://habr.com/ru/post/1795060/


All Articles