Vue-use-switch-map: a porting of the RxJS switchMap operator into the Vue composition world

This package is designed for binding refs to Vue composition functions, which, in turn, may produce one or more refs. The behaviour is similar to the RxJS switchMap operator.

Brief, simple, example:

import { useSwitchMap } from "vue-use-switch-map"
import { ref } from "vue"

const counterRef = ref(0)

const switchMappedRef = useSwitchMap(counterRef, (value) => {
    const multRef = ref(value)

    setInterval(() => {
        multRef.value = value + multRef.value
    }, 500)

    return multRef
})

Here we have a numeric ref that is combined with a function, that is a Vue 3 composition, which produces the next multiple of a number every 500ms. If we increase the value of counterRef , the emission of its multiples should start from scratch starting from the new value, and switchMappedRef should be updated accordingly. useSwitchMap will take care of situations like this.

Here is a visualization of switchMappedRef.value, as time goes by:

0 -> 0 -> 0 -> 0 -> ...

At a some point, counterRef.value got increased by one. That’s what we’ll find in switchMappedRef.value:

1 -> 2 -> 3 -> 4 -> ...  

If counterRef.value got increased again, we’ll see:

2 -> 4 -> 6 -> 8 -> ...

 

That was a simple example, but very interesting stuff can be built!
There is also the possibility to bind a ref to a function from values to objects containing refs, plus a cleanup capability and some magic here and there.

Here is the GitHub link :slightly_smiling_face:: https://github.com/jfet97/vue-use-switch-map