2

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:

  1. is it worth changing Subscription -> BehaviorSubject?

    1. Is it better to have list of Subscriptions instead of one now?
    2. How to set initial value to Subscription on subscribe?
    3. 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;
            })
        );
    }
    

    }

Macko
  • 906
  • 3
  • 11
  • 27
  • 1
    If your application is enterprise or is huge enough, consider using **Flux** architecture. I am using it on daily basis, and it works great with larger applications (~300 containers, ~1500 components). – web.dev Feb 12 '19 at 08:45
  • is it hard to switch thinking and coding to use Flux? – Macko Feb 12 '19 at 14:02
  • Not at all, tbh. It's just hard to begin with that, but it's really easy. – web.dev Feb 13 '19 at 15:03

0 Answers0