Search code examples
angulartypescriptrxjsbehaviorsubject

Using a single subscription variable with BehaviorSubject


I use BehaviorSubject in my Angular app and I get observable to my Details component from DataService as shown below:

DataService.ts:

export class DataService {

    private messageTracker = new BehaviorSubject<any>();
    private fileTracker = new BehaviorSubject<any>();

    getMessageTracker(): Observable<any> {
        return this.messageTracker.asObservable();
    }

    getFileTracker(): Observable<any> {
        return this.fileTracker.asObservable();
    }

    //set methods omitted for brevity
}


DetailComponent :

export class DetailComponent implements OnInit {

    subscription; //??? Can I use this variable for every subscription below?

    constructor(private dataService: DataService) { }

    ngOnInit(): void {

        this.subscription = this.dataService.getMessageTracker().subscribe((param: any) => {
                //...  
        });

        this.subscription = this.dataService.getFileTracker().subscribe((param: any) => {
            //...
        });
    }
}

ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

My questions are:

1) As far as I know, as above, I should create a new BehaviorSubject variable for each event e.g. messageCreateTracker (for tracking a new message added), fileCreateTracker (for tracking a new file added, messageUpdateTracker (for tracking a message updated). Is that all true?

2) Looking DetailComponent, I just used a single subscription variable for every subscriptions of Observables. Is that a bad approach? Should I create a new subscription variable for each subscriptions in ngOnInit()?


Solution

  • Answer For Query 1:

    It depends on the developer's coding style, or how he thought, you can also pass the type of event and data with that, in that case, you will need only one BehaviorSubject, like this :

    this.messageTracker.next({ type : 'create' ,  data });
    this.messageTracker.next({ type : 'update' ,  data });
    this.messageTracker.next({ type : 'delete' ,  data });
    

    But this can also create a complexity if it goes large, gain depends on the requirements of the project, your way is also good.


    Answer For Query 2:

    Basically, you can't handle multiple subscriptions like that it will override the previous one and it will only unsubscribe the last one :

    So you can create multiple variables for that OR single array/object of your subscription and then unsubscribe all :

    With Array :

    this.subscription = [];
    this.subscription.push(this.dataService.getMessageTracker().subscribe((param: any) => {}));    
    this.subscription.push(this.dataService.getFileTracker().subscribe((param: any) => {}));
    
    ngOnDestroy(): void {
        this.subscription.forEach(sub => {
            sub.unsubscribe();
        })
    }
    

    With Object :

    this.subscription = {};
    this.subscription['messageTracker'] = this.dataService.getMessageTracker().subscribe((param: any) => {}));
    this.subscription['fileTracker'] = this.dataService.getFileTracker().subscribe((param: any) => {}));
    
    this.subscription['fileTracker'].unsubscribe(); // <--- You can also do
    delete this.subscription['fileTracker']; // <--- then dont forgot to remove, or will throw error in ngOnDestroy
    
    ngOnDestroy(): void {
        for(key in this.subscription) {
          this.subscription[key].unsubscribe();
        }
    }