April 02 2019

Vue.js + RxJS - Communicating Between Components with Observable & Subject

Built with Vue 2.6.10 and RxJS 6.4.0

Other versions available:

This is a quick tutorial to show how you can communicate between components in Vue.js with RxJS. The tutorial example uses Webpack 4 for compiling + bundling the Vue.js components and is styled with bootstrap 4.

While RxJS is typically thought of as being used with Angular projects, it's a completely separate library that can be used with other JavaScript frameworks like Vue.js and React.

When using RxJS with Vue.js, the way to communicate between components is to use an Observable and a Subject (which is a type of observable), I won't go too much into the details about how observables work here since it's a big subject, but in a nutshell there are two methods that we're interested in: Observable.subscribe() and Subject.next().

Observable.subscribe()

The observable subscribe method is used by Vue.js components to subscribe to messages that are sent to an observable.

Subject.next()

The subject next method is used to send messages to an observable which are then sent to all Vue.js components that are subscribers (a.k.a. observers) of that observable.


Vue.js + RxJS Component Communication Tutorial Example

Here's a simple example showing communication between a Vue.js home page component and a root app component via a message service using RxJS observables.

The tutorial code is available on GitHub at https://github.com/cornflourblue/vue-rxjs-communicating-between-components

Here it is in action: (See on CodeSandbox at https://codesandbox.io/s/48j8596q1x)


Running the Vue.js + RxJS Component Communication Example Locally

  1. Install NodeJS and NPM from https://nodejs.org/en/download/.
  2. Download or clone the tutorial project code from https://github.com/cornflourblue/vue-rxjs-communicating-between-components
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the command line in the project root folder.


Vue.js + RxJS Message Service

With the message service you can subscribe to new messages in any component with the getMessage() method, send messages from any component with the sendMessage(message) method, and clear messages from any component with the clearMessages() method.

Note: The clearMessages() method actually just sends an empty message by calling subject.next() without any arguments, the logic to clear the messages when an empty message is received is in the app component below.

import { Subject } from 'rxjs';

const subject = new Subject();

export const messageService = {
    sendMessage: message => subject.next({ text: message }),
    clearMessages: () => subject.next(),
    getMessage: () => subject.asObservable()
};


Vue.js + RxJS App Component that Receives Messages

The Vue.js app component uses the message service to subscribe to new messages and push them into the messages array which is displayed as a list of alert divs in the component template. If an empty message is received then the messages array is cleared which automatically removes the messages from the UI.

<template>
    <div class="jumbotron">
        <div class="container text-center">
            <div class="row">
                <div class="col-sm-8 offset-sm-2">
                    <div v-for="(message, index) in messages" :key="index" class="alert alert-success">{{message.text}}</div>
                    <router-view></router-view>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { messageService } from '@/_services';

export default {
    name: 'app',
    data () {
        return {
            messages: []
        };
    },
    created () {
        // subscribe to home component messages
        this.subscription = messageService.getMessage().subscribe(message => {
            if (message) {
                // add message to local state if not empty
                this.messages.push(message);
            } else {
                // clear messages when empty message received
                this.messages = [];
            }
        });
    },
    beforeDestroy () {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
};
</script>


Vue.js + RxJS Home Component that Sends Messages

The Vue.js home component uses the message service to send messages to the app component and clear messages.

<template>
    <div>
        <h2>Vue.js + RxJS Component Communication</h2>
        <button @click="sendMessage()" class="btn btn-primary">Send Message</button>
        <button @click="clearMessages()" class="btn btn-secondary">Clear Messages</button>
    </div>
</template>

<script>
import { messageService } from '@/_services';

export default {
    methods: {
        sendMessage() {
            // send message to subscribers via observable subject
            messageService.sendMessage('Message from Home Page Component to App Component!');
        },
        clearMessages() {
            // clear messages
            messageService.clearMessages();
        }
    }
};
</script>


Web Development Sydney

Feel free to contact me if you're looking for a web developer in Sydney, I also provide remote contracting services for clients outside Sydney.