How to integrate RxJS with Vue using Vue-Rx plugin

In this tutorial, grokonez.com will show you way to integrate RxJS with Vue using Vue-Rx plugin.

Related Post: Introduction to RxJS – Extensions for JavaScript Reactive Streams

What is RxJS

Reactive Extensions for JavaScript (RxJS) is a precise alternative for callback or Promise-based libraries. It treats any ubiquitous source of events in the exact same manner, whether it is reading a file, making an HTTP call, clicking a button, or moving the mouse. RxJS is built on top of the pillars of functional and reactive programming, as well as a few popular design patterns such as Observer and Iterator.

For more details, please visit:
Introduction to RxJS – Extensions for JavaScript Reactive Streams

Way to integrate RxJS with Vue

Technology

– Vue 2.5
– RxJS 6
– Vue-Rx 6

Install RxJS & Vue-Rx plugin

First, we need to install RxJS and Vue-Rx in our Vue App.
Run command: npm install rxjs vue-rx

Add Vue-Rx plugin to Vue instance

Now we use the Vue-Rx plugin with Vue.use(). It makes an internal call to the plugin’s install() method
Open src/main.js:

import Vue from 'vue';
import App from './App.vue';
import VueRx from 'vue-rx';
import RxJS from 'rxjs';

Vue.use(VueRx, RxJS);

new Vue({
  el: '#app',
  render: h => h(App)
})

Vue.use(VueRx, RxJS) tells Vue to use the Vue-Rx plugin with the entire RxJS library. We can only import what we need to reduce bundle size:

import Vue from 'vue';
import App from './App.vue';
import VueRx from 'vue-rx';
// import RxJS from 'rxjs';
import { Observable, Subject } from 'rxjs';

// Vue.use(VueRx, RxJS);
Vue.use(VueRx, {
  Observable,
  Subject
});

new Vue({
  el: '#app',
  render: h => h(App)
})
Use RxJS in Vue App

Now we can use RxJS inside of Vue application. Open App.vue, import necessary modules from RxJS:

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

Then create an Observable data stream:

const features$ = of(['simple', 'feasible', 'practical', 'integrative']);

Now we declare our subscriptions as a function:

export default {
  name: 'app',
  data () {
    return {
      title: 'grokonez.com'
    }
  },
  subscriptions() {
    const features$ = of(['simple', 'feasible', 'practical', 'integrative']);
    return { features$ };
  }
}

The subscriptions() function return unique observables for each component instance:

integrate-rxjs-vue-rx-observables

Display the results

We can use v-for directive to iterate over the array and display the results:


integrate-rxjs-vue-rx-results

Source Code

integrate-vue-rxjs-example

Commands to run:
npm install
npm run dev



By grokonez | May 20, 2019.


Related Posts


1 thought on “How to integrate RxJS with Vue using Vue-Rx plugin”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*