currently our team has developed simple angular 6 app with few components and they are working correct but we know that this components are already too coupled together (they know too much about themselves). So naturally we want to move to decoupling solution like popular event / message bus inside angular 6 app.
So components instead of subsribing to each other they should only know about messa ge bus and only care about what is published to bus and subscribed to it.
This sample implementation is base on Subscription class but according to internet better solution it would be to use BehaviorSubject.
So I've got some questions:
is it worth changing Subscription -> BehaviorSubject?
- Is it better to have list of Subscriptions instead of one now?
- How to set initial value to Subscription on subscribe?
- If I want to get rid of channel and I would like to use something else like message class namespace so how can it be obtained? Is it a good approch?
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs/Rx'; import { filter, map } from 'rxjs/operators';
export interface IClassConstructor { new (...args: any[]): T; }
export interface IMessage { channel: Function; content: any; } /** simple class-based publish/subscribe message bus to provide decoupled communication of events, actions, commands */ @Injectable() export class MessageService { private message = new Subject();
public publish<T>(messageInstance: T): void { // Flux/Redux: 'dispatch' const channel = messageInstance.constructor; this.message.next({'channel': channel, 'content': messageInstance}); // Redux: {'type': string, 'payload': any } } public subscribe<T>(messageClass: IClassConstructor<T>): Observable<T> { const channel: IClassConstructor<T> = messageClass; return this.message.pipe( filter((message: IMessage) => { return message.channel === channel; }), map((message: IMessage) => { return message.content; }) ); }
}