1

I have two services with one Subject each that are emiting void after it completes creating objects. I want to merge them so that my component is informed when either one of the services emit the message.

    let subject = new Subject();
    let subject2 = new Subject();

    let obs = subject.asObservable();
    let obs2 = subject2.asObservable();

    obs.subscribe(
      {
        complete: () => console.log('completed obs')
      }
    )

    obs2.subscribe(
      {
        complete: () => console.log('completed obs2')
      }
    )

    merge([obs, obs2]).subscribe(
      {
        next: () => console.log('thanks for info about creating the object I needed, I will cleanup now'),
        complete: () => console.log('completed MERGE')
      }
    )

I receive the completed MERGE in the console and no completed obs or completed obs2. Without even emmiting anything. My problem is that this merge is completing too early. I want to use those streams (obs and obs2) for the timelife of the component.

0

1 Answer 1

1

The merge method does not accept an array. Well it does, but it doesn't do what you expect. When you give an array, it will use from to create a stream. This will emit the obs and obs2 as value, and thus resulting in two times the next being called. Because the array only has two items, the merge will also complete, because everything has been emitted.

Change to merge(obs, obs2) and you are good to go.

stackblitz

1
  • You just saved me from another 8h of pulling my hair out. Worked as expected. Thanks for explanation and solution. Cheers!
    – miszczak
    Apr 6, 2020 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.