If I have a long-running observable called longObservable
, which emits a new string once after 5 seconds and then completes.
longObservable(): Subject<string> {
return timer(5000).pipe{
map(() => randomString())
}
}
Other pages call this observable multiple times. If it's already running, I want to continue that process. If it's completed, I want to start it again.
longObservable.subscribe() // Starts the timer immediately
This is followed by another subscription two seconds later:
longObservable.subscribe() // Will get the same string as
// the previous subscription in 3 seconds.
Finally, a third subscription runs 20 seconds later:
longObservable.subscribe() // Initiates a new iteration and waits
// 5 seconds before emitting a new string.
The second subscription works as intended, but I am facing difficulties with the third one. It immediately emits the same value because longObservable
has already completed.
This setup is used for geolocation requests on a device. The goal is to request a new location, or use the existing result if a request is already in progress.
Edit: Changed the observable to a subject for multicasting and removed the take(1) operator.
Edit2: https://stackblitz.com/edit/angular-venpk4 contains a working example of what I'm trying to achieve. I hope to accomplish this without using the timerRunning variable and with the help of RxJS operators. This code can be found under the hello component and prints results to the console.