33

When speaking about Observables (especially rxjs), what is the difference between "finally" and "done" or "complete"?

Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78
Alexander Taylor
  • 16,574
  • 14
  • 62
  • 83

2 Answers2

35

Finally always happens whenever an observable sequence terminates (including errors); completed only happens when it terminates without errors.

Finally:

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/finally.md

OnCompleted:

An Observable calls this method after it has called onNext for the final time, if it has not encountered any errors.

http://reactivex.io/documentation/observable.html

"Done" isn't an rx/observables concept. I've just seen it printed in examples of "Complete" / "OnComplete".

Note: when you call subscribe, the syntax is usually:

observable.subscribe([observer] | [onNext], [onError], [onCompleted]);
// Like this:
observable.subscribe(
    (value) => { ... },
    (error) => { ... },
    () => { console.log('complete!'); }
);

or

observable.subscribe({
  next: x => console.log('got value ' + x),
  error: err => console.error('something wrong occurred: ' + err),
  complete: () => console.log('done'),
});

Whereas finally is handled like this:

observable.finally(() => { console.log('finally!'); })
          .subscribe(...) // you can still call subscribe
Alexander Taylor
  • 16,574
  • 14
  • 62
  • 83
16

To be more precise, the finally() operator adds a dispose handler. The complete notification just calls the complete handler in observers.

What this means in practise:

  • When using finally() the callback is going to be called in every situation that causes unsubscription. That's when complete and error notifications are received by observers but also when you manually unsubscribe.

    See demo: https://jsbin.com/dasexol/edit?js,console

  • complete or error handlers are called only when the appropriate notification is received. Only 0 - 1 handlers can be called but never both of them.

RafaelJan
  • 3,118
  • 1
  • 28
  • 46
martin
  • 93,354
  • 25
  • 191
  • 226