0

I have two components: CreateComment and DisplayComment. DisplayComment component has itself nested in it for displaying the threaded comments.

Now, whenever I create a comment from CreateComment component, I call a subject in CommentService to emit an event. This subject is being subscribed in the DisplayComment component in which I am pushing the comment to the comments array to be rendered.

Since I have nested components, this subscription is being called multiple times (according to the threaded comments count).

Can someone please let me know if there is any way I can restrict the subscription execution on the DisplayComment method to only one time?

Sudharsan Prabu
  • 105
  • 1
  • 11

1 Answers1

0

If you need a subscription to complete on a certain amount of emissions, you could look into RxJS take operator.

ngOnInit() {
  this.someService.someObservable.pipe(
    take(1)
  ).subscribe(
    response => {
      // do something
    }
  );
}

You could also increase the argument to the number of values you wish to be emitted before the subscription completes. For take(1) the subscription will complete after one value is emitted.

There is also a RxJS first() operator. See here for the differences between take(1) and first().

ruth
  • 29,535
  • 4
  • 30
  • 57
  • I checked both by using first() and take(1) and it is still running multiple times. This is because, I have nested the DisplayComment component internally within itself and ngOnInit will run multiple times for each threaded comment. Because of this, the subscription also will be executed multiple times for every invocation of the component. – Sudharsan Prabu Jun 05 '20 at 21:47
  • 1
    In that case, the `DisplayComment` has no knowledge of it's current state. You could setup a service to hold it's values, initialize and assign the values there. Now you could check if the value is assigned already before subscribing and assigning new values to it. – ruth Jun 05 '20 at 21:51
  • 1
    Thank you for the thought. I handled it in the server itself by passing the whole comments array in response instead of the created comment. – Sudharsan Prabu Jun 05 '20 at 22:10