Balraj Singh
Balraj Singh

Reputation: 3471

Publishing last recieved data when Observable is Subscribed

I have created GeoCoordinateReactiveService using Rx in Windows Phone 8. The problem is that I need to start Geocoordinatewatcher before I Subscribe for Observable which is observing over PositionChange event.

So if position change event is fired before I subscribe for the first time I won't be getting the last data. How can I change current implementation to do so.

below is my current code:

 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);

Upvotes: 0

Views: 85

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79441

Option 1

Subscribe before starting your watcher:

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

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

geoCoordinateWatcher.Start();

Since you have given limited information, I have no reason to believe this is insufficient.

Option 2

Use Replay to define an IConnectableObservable<T>, then Connect prior to starting your watcher:

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);

This second option is necessary if you really do need to perform your subscription at a later time than you start your watcher.

Upvotes: 1

Related Questions