在Observable被订阅时发布最后收到的数据

时间:2015-08-18 15:17:31

标签: c# wpf silverlight system.reactive reactive-programming

我在Windows Phone 8中使用Rx创建了GeoCoordinateReactiveService。 问题是我需要在订阅Observable之前启动Geocoordinatewatcher,它正在观察PositionChange事件。

因此,如果在我第一次订阅之前触发了职位变更事件,我将无法获得最后的数据。如何更改当前实现。

下面是我目前的代码:

 this.StatusObservable = Observable
            .FromEventPattern<GeoPositionStatusChangedEventArgs>(
                handler => geoCoordinateWatcher.StatusChanged += handler,
                handler => geoCoordinateWatcher.StatusChanged -= handler)
            .Select(ep => ep.EventArgs.Status);

 this.PositionObservable = Observable
            .FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
                handler => geoCoordinateWatcher.PositionChanged += handler,
                handler => geoCoordinateWatcher.PositionChanged -= handler)
            .Select(ep => ep.EventArgs.Position);

geoCoordinateWatcher.Start();


geoCoordinateService.StatusObservable
            .ObserveOnDispatcher()
            .Subscribe(this.OnStatusChanged);

geoCoordinateService.PositionObservable
            .ObserveOnDispatcher()
            .Subscribe(this.OnPositionChanged);

1 个答案:

答案 0 :(得分:1)

选项1

在开始观察者之前订阅:

geoCoordinateService.StatusObservable
            .ObserveOnDispatcher()
            .Subscribe(this.OnStatusChanged);

geoCoordinateService.PositionObservable
            .ObserveOnDispatcher()
            .Subscribe(this.OnPositionChanged);

geoCoordinateWatcher.Start();

由于您提供的信息有限,我没有理由相信这是不够的。

选项2

在启动观察者之前,使用Replay定义IConnectableObservable<T>,然后Connect

var status = geoCoordinateService.StatusObservable.Replay(1);
var position = geoCoordinateService.PositionObservable.Replay(1);

var statusConnection = status.Connect();
var positionConnection = position.Connect();

geoCoordinateWatcher.Start();

status.ObserveOnDispatcher().Subscribe(this.OnStatusChanged);
position.ObserveOnDispatcher().Subscribe(this.OnPositionChanged);

如果您确实需要在比启动观察者更晚的时间执行订阅,则需要第二个选项。

相关问题