If I have an observable that takes a long time to execute. We will call it longObservable
which is of type Observable, takes 5 seconds to execute, and each time it executes it emits a new string only once then completes.
longObservable(): Subject<string> {
return timer(5000).pipe{
map(() => randomString())
}
}
And some other pages call it multiple times. If it's in process, I'd like to just continue that one process. If it's complete, I'd like to start it again.
longObservable.subscribe() // Immediate, start the timer
and this runs two seconds later:
longObservable.subscribe() // Get the same string as
// the above subscription in 3 seconds.
and this runs 20 seconds later
longObservable.subscribe() // Start a new iteration and wait
// 5 seconds, get a new string.
The second subscribe I think is easy, it'll work how I want. It's the 3rd one that I'm having trouble with. It will emit the same value as the other two immediately since longObservable
is complete.
This is being used for geolocation on a device. I want to request a new location, but if there is already a request in progress, just use that result.
Edit: Changed observable to subject for multicasting, removed take(1).
Edit2: https://stackblitz.com/edit/angular-venpk4 here is a working example of what I want. I'm hoping to accomplish this without the timerRunning variable and with RxJS operators. It's under the hello component and prints to the console.
take(1)
in your example is not necessary – Jota.Toledo