Rxjs: finalize: pass the last emitted value to the callback

Created on 20 May 2019  路  2Comments  路  Source: ReactiveX/rxjs

Feature Request

Is your feature request related to a problem? Please describe.
When my observable completes, errors, or gets unsubscribed, I need to do a cleanup using the last emitted value.

Describe the solution you'd like
I'd like to get the last emitted value as an argument to finally's callback

Describe alternatives you've considered
All the alternatives look too clumsy.

Additional context
Another issue about adding a callback argument to finalize: #2823

Most helpful comment

You can compose this pretty easily with existing operators:

https://stackblitz.com/edit/rxjs-fkavym

function finalizeWithValue<T>(callback: (value: T) => void) {
  return (source: Observable<T>) => defer(() => {
    let lastValue: T;
    return source.pipe(
      tap(value => lastValue = value),
      finalize(() => callback(lastValue)),
    )
  })
}

I agree with @cartant that this should probably be a user land thing.

All 2 comments

IMO, this is something that should be handled in a user-land operator or observable. I don't think it's something that should be added to finalize.

You can compose this pretty easily with existing operators:

https://stackblitz.com/edit/rxjs-fkavym

function finalizeWithValue<T>(callback: (value: T) => void) {
  return (source: Observable<T>) => defer(() => {
    let lastValue: T;
    return source.pipe(
      tap(value => lastValue = value),
      finalize(() => callback(lastValue)),
    )
  })
}

I agree with @cartant that this should probably be a user land thing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

peterbakonyi05 picture peterbakonyi05  路  4Comments

unao picture unao  路  4Comments

haf picture haf  路  3Comments

benlesh picture benlesh  路  3Comments

benlesh picture benlesh  路  3Comments