none
About disposing the IObservable

    Question

  • Hi,

    i have written code like below that basically sets the private field start to the current datetime when de Geolocator reports that the GPS device is ready.

    Observable.FromEventPattern<TypedEventHandler<Geolocator, StatusChangedEventArgs>, Geolocator, StatusChangedEventArgs>
                    (
                        handler => watcher.StatusChanged += handler,
                        handler => watcher.StatusChanged -= handler
                    )
                .Select(e => e.EventArgs.Status)
                .Where(e => e == PositionStatus.Ready)
                .Take(1)
                .Subscribe(e => start = DateTime.Now);

    As far as I know the code "e => start = DateTime.Now" will only run once. Do I have to dispose the IObservable here or will the Take(1) take care of unregistering the StatusChanged event?

    Sunday, January 12, 2014 5:19 PM

Answers

  • The event will be unsubscribed after the first element automatically.

    However, as a good practice, you should dispose the observable subscription when you no longer need it. Consider the scenario if the StatusChanged event is not triggered or it is triggered only with PositionStatus different from Ready. In this case you would never unsubscribe the event, thus causing a memory leak.

    • Marked as answer by Expecho Friday, January 24, 2014 10:11 AM
    Friday, January 24, 2014 8:47 AM