Observables in Angular

Damaris Göbel
1 min readMar 23, 2023

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes.

Your application code only needs to worry about subscribing to consume values, and when done, unsubscribing.

Create an Observable that will start listening to geolocation updates when a consumer subscribes.

// Create an Observable that will start listening to geolocation updates
// when a consumer subscribes.
const locations = new Observable((observer) => {
let watchId: number;

// Simple geolocation API check provides values to publish
if ('geolocation' in navigator) {
watchId = navigator.geolocation.watchPosition((position: GeolocationPosition) => {
observer.next(position);
}, (error: GeolocationPositionError) => {
observer.error(error);
});
} else {
observer.error('Geolocation not available');
}

// When the consumer unsubscribes, clean up data ready for next subscription.
return {
unsubscribe() {
navigator.geolocation.clearWatch(watchId);
}
};
});

// Call subscribe() to start listening for updates.
const locationsSubscription = locations.subscribe({
next(position) {
console.log('Current Position: ', position);
},
error(msg) {
console.log('Error Getting Location: ', msg);
}
});

// Stop listening for location after 10 seconds
setTimeout(() => {
locationsSubscription.unsubscribe();
}, 10000);

Further reading: https://angular.io/guide/observables

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Damaris Göbel
Damaris Göbel

Written by Damaris Göbel

I like to do crazy things with CSS & JavaScript. My brain occasionally runs out of memory so I need to write down my thoughts.

No responses yet

Write a response