Search code examples
angularrxjsangular7angular-reactive-forms

Multiple subscriptions to same Observable


I have several subscriptions in one of the components in my application and I could see that there are several instances where we are subscribing to same observable repetitively.

One issue that I recently came across is setting a value for one control in one subscription logic is conflicting with another and both subscriptions are on same observable's. we have fixed that issue by adding more specific conditions to avoid conflicts but it made me wonder subscribing to same observable combination repetitively is really a good practice (I assume we could just write all logic in single subscriber)? Could it cause any performance issues in the long run as App grows?

    combinelatest(observable1, observable2).pipe(
    tap(() = > {
    // do some logic
    // update Property1 to foo
    })
    ).subscribe();

    combinelatest(observable1, observable2).pipe(
    tap(() = > {
    // do some logic
    })
    ).subscribe();

    combinelatest(observable1, observable2, observable3).pipe(
    tap(() = > {
    // do some logic
    // // update Property1 to foofoo
    })
    ).subscribe();

observable1.pipe(
    tap(() = > {
    // do some logic
    })
    ).subscribe()

Any guidance is much appreciated.


Solution

  • There is nothing wrong with subscribe multiple times on a share observable. However having say that, often observable can be split up with sense to be reused and there is no fix rule on the granularity of each observable, each observable should be defined to fit your application requirement

    for example we have a get blog post button if you want multiple component to listen to that event you can just do

    const onGetPostClick=fromEvent(button,'click')
    

    then you want to execute get post http call and also allow other component to listen to such event.

    const onGetPost=onGetPostClick.pipe(mergeMap(e=>fetch()....),share())
    

    if you only interested in post in news category

    const onGetNews=onGetPost.pipe(filter(post=>post.cat==='news'))
    

    give meaning to each observable you will find your code much more DRY and minimal