给定:
public partial class Weather
{
private readonly DispatcherTimer _timer = new DispatcherTimer();
private readonly IWeatherDataProvider _weatherDataProvider;
public Weather(IWeatherDataProvider weatherDataProvider)
{
InitializeComponent();
_weatherDataProvider = weatherDataProvider;
Loaded += async (sender, args) =>
{
_timer.Interval = new TimeSpan(0, 15, 0);
_timer.Tick += async (o, eventArgs) => DataContext = await UpdateWeather();
_timer.Start();
DataContext = await UpdateWeather();
};
Unloaded += (sender, args) => _timer.Stop();
}
private async Task<WeatherData> UpdateWeather()
{
var weatherData = await _weatherDataProvider.GetWeather();
return weatherData;
}
}
我很困惑如何转换这个使用反应式扩展。我从:
var weather = Observable.FromAsync(_weatherDataProvider.GetWeather);
但是当我进入投票部分时:
Observable.Timer(new TimeSpan(0, 15, 0)).Subscribe(weather);
没有通用重载。我想我明白我需要生成一个序列的想法,但由于某种原因我无法弄清楚它。
具有
Select
投影的Observable.Interval
是关键。像这样:
public class Weather
{
private readonly IWeatherDataProvider _weatherDataProvider;
private CompositeDisposable disposables = new CompositeDisposable();
public Weather(IWeatherDataProvider weatherDataProvider)
{
InitializeComponent();
_weatherDataProvider = weatherDataProvider;
Loaded += (sender, args) =>
{
var weather = Observable.Interval(TimeSpan.FromMinutes(15))
.SelectMany(_ => weatherDataProvider.GetWeather().ToObservable())
.ObserveOnDispatcher()
.Subscribe(data => DataContext = data);
disposables.Add(weather);
};
Unloaded += (sender, args) => disposables.Dispose();
}
}
ObserveOnDispatcher
位于 nuget 包 rx-xaml 中。