简体   繁体   中英

How do I correctly timing out an observable?

Using an observable from event, I download the latest weather from a web service. I tested this out on the phone and emulator at home and it works fine. I brought the project with me to work and ran it using the emulator there. Now i'm not sure it its a firewall or what but it doesn't seem to get the weather, it just sits there forever, trying. So it got me thinking that if this was ever to happen on a phone then I need some kind of timeout in that if it can't get the weather in say 10 - 15 seconds then just give up.

Here is the example code so far

IObservable<IEvent<MyWeather.GetWeatherCompletedEventArgs>> observable =
          Observable.FromEvent<MyWeather.GetWeatherCompletedEventArgs>(Global.WeatherService, "MyWeather.GetWeatherCompleted").Take(1);

        observable.Subscribe(w =>
        {

            if (w.EventArgs.Error == null)
            {
               // Do something with the weather
            }
        });

        Global.WeatherService.GetWeatherAsync(location);

How can I get this to time out safely after a given time if nothing is happening?

You should use FromEventPattern (not FromEvent ) so I've changed your observable to:

var observable =
      Observable
        .FromEventPattern<MyWeather.GetWeatherCompletedEventArgs>(
            Global.WeatherService, 
            "MyWeather.GetWeatherCompleted")
        .Take(1);

You could then do this:

var timeout =
    Observable
        .Timer(TimeSpan.FromSeconds(10.0))
        .Select(_ => (EventPattern<MyWeather.GetWeatherCompletedEventArgs>)null);

observable
    .Amb(timeout)
    .Subscribe(w =>
    {
        if (w != null && w.EventArgs.Error == null)
        {
           // Do something with the weather
        }
    });

How about Observable.Timeout ? It should do what you want, or?

observable.Subscribe(w => ...).Timeout(TimeSpan.FromSeconds(10)).Catch<>(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM