1//Put an object in a observable
2let myObj = {name: "Maria", age: 23};
3this.myObs$ = of(myObj);
1
2 content_copy
3
4 // Create an Observable that will start listening to geolocation updates
5// when a consumer subscribes.
6const locations = new Observable((observer) => {
7 let watchId: number;
8
9 // Simple geolocation API check provides values to publish
10 if ('geolocation' in navigator) {
11 watchId = navigator.geolocation.watchPosition((position: Position) => {
12 observer.next(position);
13 }, (error: PositionError) => {
14 observer.error(error);
15 });
16 } else {
17 observer.error('Geolocation not available');
18 }
19
20 // When the consumer unsubscribes, clean up data ready for next subscription.
21 return {
22 unsubscribe() {
23 navigator.geolocation.clearWatch(watchId);
24 }
25 };
26});
27
28// Call subscribe() to start listening for updates.
29const locationsSubscription = locations.subscribe({
30 next(position) {
31 console.log('Current Position: ', position);
32 },
33 error(msg) {
34 console.log('Error Getting Location: ', msg);
35 }
36});
37
38// Stop listening for location after 10 seconds
39setTimeout(() => {
40 locationsSubscription.unsubscribe();
41}, 10000);
42