Reputation: 5
I need the help in the following vue-rx / RxJs question.
I have to make a subscription in vue-rx that watches a props value, and when it is true then it calls a http request in every 500 ms, and stops it when it is false, or when the returned value is 'COMPLETED'.
I tried something like this:
export default {
props: ['started'],
subscriptions() {
return {
currentHttpState: this.$watchAsObservable('started')
.pipe(pluck('newValue'),filter(value => value === false))
.switchMap(() => interval(500).pipe(switchMap(() => this.callHttpRequest()),distinctUntilChanged())),
Thank you for the help!
Upvotes: 0
Views: 393
Reputation: 8022
I'm not too familiar with vue (or vue-rx), so this may just be half the answer (the RxJS bit).
I'm assuming this.$watchAsObservable('started')
with pluck('newValue')
is a stream of true
and false
? (reflecting the value of the started
prop)
If so, I would use switchMap to switch between an interval/timer and nothing.
currentHttpState: this.$watchAsObservable('started').pipe(
pluck('newValue'),
map(val => val? timer(0,500) : EMPTY),
switchMap(timer$ => timer$.pipe(
switchMap(_ => this.callHttpRequest()),
takeWhile(result => result.status !== 'COMPLETED')
)
)
that second switchMap will have the effect that if a call takes over 500ms to complete, it will be dropped and you'll never see the results. This also unsubscribed if the takeWhile()
condition isn't met - so you'll have to change that to meet your specific requirements.
Upvotes: 0