Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable, am I doing it right?

I have this service:

 getPosition(): Observable<Object> {
    return Observable.create(observer => {
        navigator.geolocation.watchPosition((pos: Position) => {
            observer.next(pos);
            observer.complete();
        }),
        () => {
            console.log('Position is not available');
        },
        {
            enableHighAccuracy: true
        };
    });
}

I want to use it like this:

this.getLocationService.getPosition().subscribe((pos: Position) => {
        self._latitude = pos.coords.latitude;
        self._longitude = pos.coords.longitude; }

But unfortunately it does not work. I assumed every time position changes, the lat and long would change. But it does not work.

like image 459
adam nowak Avatar asked Feb 06 '23 23:02

adam nowak


1 Answers

One issue here is related to Observable contract

The Observable Contract

“The Observable Contract,” which you may see referenced in various places in source documentation and in the pages on this site, is an attempt at a formal definition of an Observable, based originally on the 2010 document Rx Design Guidelines from Microsoft that described its Rx.NET implementation of ReactiveX. This page summarizes The Observable Contract.

Notifications

An Observable communicates with its observers with the following notifications:
  • OnNext
    conveys an item that is emitted by the Observable to the observer
  • OnCompleted
    indicates that the Observable has completed successfully and that it will be emitting no further items
  • ...

So, if you want to continue to fire events, you should not call completed

 getPosition(): Observable<Object> {
    return Observable.create(observer => {
        navigator.geolocation.watchPosition((pos: Position) => {
            observer.next(pos);
            // simply call next again, but not complete
            // until position is completed
            //observer.complete();
        }),
        ...
like image 114
Radim Köhler Avatar answered Feb 09 '23 22:02

Radim Köhler