How to create RxJS Publish Subscribe Library?
Did you know you can create your own publish-subscribe library for your RxJS project? By using BehaviorSubject
and filter
operator it is possible to create your first pub sub library. Publish and Subscribe framework is very helpful to create isolated modules. Therefore, I will explain and demonstrate you how can you create your own pub sub library.
Model Each message as Action
In your project model every messages as action. Imagine whatever events are happening, any user interactions, any side effects etc everything as Action. It is an abstraction over events
and commands
. An Action can look like below.
The Action File
Action can have type so that you can identify them independently. Your action can have other properties as you wish like payload
etc.
export interface Action {
type: string;
}
export const INIT = 'myapp [init]';
export const initAction = { type: INIT }
INIT
is an action type indicates that your application is initiated. This is just an example you can create your own Action Type. Finally initAction
is an action.
How to manage all Actions within Your App?
We do not want the actions to be produce repetitively whenever a new subscriber subscribes for the same action type. Therefore, we have to make our actions Hot
Observable. Also we want to start up our pub sub framework with an INIT
action to indicate our library and app both are ready. Hence I will use BehaviorSubject
from RxJS.
import { BehaviorSubject } from 'rxjs';
import {initAction, Action} from './action';
export const actions$ = new BehaviorSubject<Action>(initAction);
Now we are ready to publish and filter desired action on our action stream.
Manage Publish an Action
export const publish = (action) => actions$.next(action);
publish
is a method that will next on our actions$
subject. So that whoever else has subscribed to this action will get their subscription callback method invoked with the action.
Manage Filtering Desired Action
Now its time to allow filtering desired action from the stream of actions actions$
I will use filter
operator from RxJS and do filter by matching type
of action. Therefore, let me create a new method called as ofType
export const ofType = (actionType) => actions$.pipe(filter(a => a.type === actionType));
Pub Sub Final Code
Our library work is done and here is my final code.
// action.ts
export interface Action { type: string; } export const INIT = 'myapp [init]';
export const initAction = { type: INIT };
// actions.ts
import { BehaviorSubject } from 'rxjs'; import {initAction, Action} from
'./action'; import { filter } from 'rxjs/operators';
export const actions$ = new BehaviorSubject<Action>(initAction);
export const publish = (action) => actions$.next(action);
export const ofType = (actionType) => actions$.pipe(filter(a => a.type ===
actionType));
How to consume RxJS actions?
This is very interesting and simple. I am very excited to show you this in action. Lets first try to listen to INIT
action and react on it.
import * as actions from './actions';
import { INIT } from './action';
actions.ofType(INIT).subscribe((action)=>{ console.log('received message',
action); // You can do your project initial setup here // like brining some data
from server etc. });
Next I will show you how can you create your own action and do pub sub. In the below example I have created addUserAction
and did pub sub on it checkout.
const ADD_USER = 'users [add]';
actions.ofType(ADD_USER).subscribe((action) => {
console.log('received message', action);
});
const addUserAction = { type: ADD_USER, payload: { id: 23, firstName: 'Rupesh' }
}; actions.publish(addUserAction);
Conclusion
My focus is to learn RxJS by implementing it in real world use. This example for doing publish subscribe using RxJS was very helpful to learn BehaviorSubject
and filter
operator. Also it solved one of the most demanded need for RxJS app is to do pubsub. Many of you might be aware of ngrx
Library there also they use actions$
as an injectable service where you can subscribe to any action and perform operations. I hope you enjoyed this and learned something new and simple. See you soon... Happy Coding!
Code Base
https://stackblitz.com/edit/rxjs-pub-sub-rt
https://stackblitz.com/edit/rxjs-pub-sub-rt?embed=1&file=index.ts
message from rupesh tiwari
enroll in full stack master link
❤️ Hey Viewers! show your support & subscribe to full stack master school to watch full stack JavaScript HD course videos including node.js, angular, express, webpack and much more. Download source code, slides and step by step guide. Learn more at https://blog.rupeshtiwari.com/subscribe 💥 I am super excited to teach you at Full Stack Master!
Comments