A,

This article will not explain how RxJS works, but how to integrate RxJS in VUE

1. Master RxJS in 30 days

RxJS – This is a tutorial about RxJS written by a Taiwanese developer. The tutorial covers principle parsing, simple implementation, and the introduction of common operators.

2. Learn RxJS operator

The functions and examples of various common operators can be found in the official documentation of RxJS.

Vue simply integrates RxJS

To use RxJS in Vue, all you need is the following reference, of course, more reference methods can be referred to the official documentation, such as import on demand

import Rx from 'rxjs/Rx'If you want a better experience with RxJS in vue, it is recommended to use vue-rx, the officially maintained library, as follows: import vue from'vue'
import VueRx from 'vue-rx'
import Rx from 'rxjs/Rx'

Vue.use(VueRx, Rx)
Copy the code

This means that the Vue instance has a hook function which subscriptions subscriptions only. Its usage is similar to data, as shown below:

<template> <div> <span> <span> <span> age: {{age$}}</span> <button V-stream :click="setName$"</button> </div> </template> <script>export default {
    domStreams: [
        'setName$'].subscriptions () {
        return {
            age$: Rx.Observable.of(23)
                .map(data => data),
            name$: this.setName$
                .map(e => 'myName')
                .startWith(' ')
        }
    }
}
</script>
Copy the code

As shown above, rx.observable. Of (23) emits a value of 23 when subscribed, and this.setName$is a stream event defined in domStreams, which is actually a Subject (see the RxJS definition of Subject). When the user clicks a button, it emits data from the source of the click, as in the Map Operator above, which receives an event object from the data source (we don’t use this object here, but simply return a string ‘myName’ we defined). StartWith initializes the name$as an empty string, and vue-rx already does an implicit subscribe binding for us, so the value 23 is immediately assigned to the last value of age$, which is then bound to the view, and in this case, We can think of age$and name$as the result of an observable flow emitted by a data source that is responsive, with the initial emitted values being processed by various operators and then returned to the page.

3. Use RxJS after vuE-RX integration

Making the address

The project takes parcel build, examples including native versus integrated vue-rx use, how events are used, and examples of common operators (including use scenario selection of switchMap, concatMap, haustmap, etc.)

Create Observeble

<template> <div> <h3>demo2 create convert data to Observable </h3> <p> String: {{STR $}}</p> <p> array: <span v-for="(num, index) in arr$" :key="index"> {{num}} < / span > < / p > < p > object: {{obj $. A}} < / p > < p > Boolean value: {{bool $}} < / p > < p > promise: {{promise $}} < / p > < p > the interval: {{ interval$ }}</p> </div> </template> <script> import Rx from'rxjs/Rx'

export default {
  subscriptions () {
    return{/** * common datatype can be converted with of ** Promise objects can be used from or fromPromise * interval can emit incremented numbers within a given interval */ STR $: rx.observable. Of ('str'),
      arr$: Rx.Observable.of([1, 2, 3]),
      obj$: Rx.Observable.of({ 
        a: 'test-obj' 
      }),
      bool$: Rx.Observable.of(true),
      promise$: Rx.Observable.fromPromise(this.getPromise()),
      interval$: Rx.Observable.interval(1000)
    }
  },
  methods: {
    getPromise () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('promise')
        }, 1000)
      })
    }
  }
}
</script>
Copy the code

After you create a data flow, you can use the same method as data to bind the results of the data flow to the view

2. Use of events

// VuE-rx is not integratedexportdefault { ... // The dom file must be mountedmounted() {// fromEvent converts dom binding events to Observable rx.Observable. fromEvent(this) {// fromEvent converts dom binding events to Observable rx.Observable. fromEvent(this).$refs['btn'].'click')
      .subscribe(e => {
        this.data = 'Data was obtained successfully'})},... <template> <button class="btn" v-stream:click="getData$"</button> </template> <script>exportdefault { ... // The v-stream event can be written in the same way as domStreams: ['getData$'].subscriptions () {
    return{data$: this.getData$// map operator is used to map data. Here we return a string.return 'Data was obtained successfully'
        })
    }
  }
}
</script>
Copy the code

3. Use switchMap, concatMap, and haustmap

These operators are usually used in conjunction with HTTP requests. Let’s look at some simple uses. Click to map the current stream to a new stream

<template> <div> <h3> <button class="btn" v-stream:click="getConcatMapCount$"<p>{{concatMapCount$</button> </p> <button class="btn" v-stream:click="getSwitchMapCount$"SwitchMapCount $</button> <p>{{switchMapCount$}}</p> <button class="btn" v-stream:click="getExhaustMapCount$"Haustmapcount $</button> <p>{{haustmapcount $}}</p> </div> </template> <script> import Rx from'rxjs/Rx'

export default {
  data () {
    return {
      count: 0
    }
  },
  domStreams: [
    'getConcatMapCount$'.'getSwitchMapCount$'.'getExhaustMapCount$'].subscriptions() {/** * The following operator converts one Observable to another * continues processing data by returning an observation stream */returnConcatMapCount$: this.getConcatMapCount$. ConcatMap ((e) => {returnRx.observable. from(this.getCount())}), /** * If you click the button multiple times, the switchMap will only issue the last value, and the previous value will be processed */ switchMapCount$: this.getSwitchMapCount$ .switchMap((e) => {returnRx.observable. From (this.getcount ())}), /** * When you click the button several times in succession, haustmap is executed only once, and you can click the next haustmap only after the first value is emitted */ haustmapcount $: this.getExhaustMapCount$ .exhaustMap(e => {return Rx.Observable.from(this.getCount())
        })
    }
  },
  methods: {
    getCount () {
      return new Promise((resolve, reject) => {
        this.count++
        setTimeout(() => {
          resolve(this.count)
        }, 2000)
      })
    }
  }
}
</script>
Copy the code

The getCount above is treated as an HTTP request that will be answered after 2 seconds, and the map operators will behave differently when you click consecutively.

For example, concatMap will send an increasing count every two seconds after multiple clicks, whereas switchMap will only send the count of the last click after multiple clicks. For example, if I clicked 3 times, switchMapCount$will show 3 after 2 seconds instead of 1. ExhaustMap prior to the first click no response is not performing subsequent click operation, until the response after click.

About Rx5 and Rx6

The above repository is based on the Rx5 example, but the new Rx6 API has some changes. Instead of chaincalling operators, Rx6 calls them in combination with pipe operators. The Observable reference has also been changed, please refer to the official documentation