Today I Learned

hashrocket A Hashrocket project

Unsubscribe from `watchPositionAsync` in Expo

After seeing some very unexpected behavior, I went down the rabbit hole of StackOverflow, Reddit, and finally the Expo documentation for the function watchPositionAsync.

As it turns out, I had overlooked that this function returns a promise that resolves to a LocationSubscription. Meaning the following code does NOT work for obvious reasons.

Bad ❌

import { Accuracy, watchPositionAsync } from 'expo-location';

function Actions() {
   useEffect(() => {
      const subscription = watchPositionAsync(
        { accuracy: Accuracy.Balanced },
        coords => console.log(coords)
      );
      return subscription.remove();
    }, []);
  // ...
}

In order to get the subscription object, I had to let the promise resolve. This now looks like below.

Good ✅

import { Accuracy, watchPositionAsync } from 'expo-location';

function Actions() {
   useEffect(() => {
      let subscription;
      async function watchLocation() {
        subscription = await watchPositionAsync(
          { accuracy: Accuracy.Balanced },
          coords => console.log(coords)
        );
      }
      watchLocation();
      return subscription?.remove();
    }, [])
  // ...
}

Hooray documentation! 😅

https://docs.expo.dev/versions/latest/sdk/location/#locationsubscription

See More #mobile TILs