RxJS 6: Subscribe only onComplete

Viewed 3472

I don't care about next() or error() values. Do I still need to define empty functions as callbacks in subscribe() function?

5 Answers

You can do something like this

subscribe({
  complete: () => { // do the stuff you need to do on completion }
})

subscribe allows you to pass an object with 3 properties, next error and complete, which point to the respective functions. Each of this property is optional.

In fact you can use just the following without any handler:

.subscribe()

However this doesn't handle error notifications (these will be thrown to the global error handler) so you might want to use also this to ignore all errors:

.subscribe({ error: () => {} })

In RxJS 6 this will strip away all notifications beside complete and also cause completion on error:

obs$.pipe(
    ignoreElements(),
    catchError(() => EMPTY))
.subscribe(null, null, _ => console.log("complete"));

You still need to pass empty functions or undefined for next and error in your subscribe.

you can still set

.subscribe(undefined, undefined, () => {/* On complete */})

to omit any not needed executions of subscribe

Related