问题描述:

I have a simple WPF application that contains a list of link. I would like to select few of them, add them to a an "observable list" and subscribe to it. Then the observer callback will download the link, and will proceed the next one if any of sleep.

I would also be able to update my UI to let the user know that an item has been proceeded.

Could someone give me some help doing this

Many thanks.

网友答案:

I would use Observable.FromEventPattern to first convert the list box of link selection events into an Observable of Uri.

Next, i would write an extension method to download link.

public static IObservable<bool> DownloadLink(this IObservable<Uri> source)
{
    return Observable.Create<bool>(observer =>
    {
        return source
            .Subscribe(onNext: async link =>
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    var result = await client.GetStringAsync(link);

                    if (isSuccess)
                        observer.OnNext(true);
                    else
                        observer.OnNext(false);
                }
            }, onError: observer.OnError, onCompleted: observer.OnCompleted);
    });
}

Finally, hook it up.

uriObservable.DownloadLink().ObserveOnDispatcher().Subscribe( // update ui logic here );
相关阅读:
Top