2

I need to do a some action when stream ends. What the idiomatic way to do that?

Now I use the code bellow:

source.subscribe(undefined, undefined, function() {
  socket.send({type: 'end'});
});
kharandziuk
  • 12,020
  • 17
  • 63
  • 121

1 Answers1

4

There are several ways to accomplish this:

  1. Use the operator subscribeOnCompleted() instead of passing in empty values to the .subscribe method.

  2. Use tapOnCompleted(), same as above, but it won't start the sequence and you can inject it part way through the sequence.

  3. Use the .finally() which will get executed when the sequence finishes (normally or otherwise).

  4. In your example you are showing a side effect but if you were doing clean up of resources it would be more semantic to use .using() which takes a disposable and ties it to the lifetime of the subscription.

In order these look like:

  1. source.subscribeOnCompleted(() => socket.send({type: 'end'}));

  2. source.tapOnCompleted(() => socket.send({type: 'end'})).subscribe()

  3. source.finally(() => socket.send({type: 'end'})).subscribe()

  4. Rx.Observable.using(() => createResource(), (resource) => source).subscribe()

paulpdaniels
  • 18,395
  • 2
  • 51
  • 55