BACK
Use casesReset on logout — clearing the service's state
Use cases · 42

Reset on logout — clearing the service's state

Pattern

After logout the app shouldn't keep receiving the old user's data. All user-specific streams (a notification-refresh interval, a WebSocket, a profile cache) must stop and reset.

The problem it solves

Leave the old interval running and after logout it keeps hitting the API "as Ada" while a different user is on screen. Or worse — the anonymous screen shows private data. Imperative cleanup in the logout handler is easy to forget, especially as more services are added.

Operators and why they matter

  • switchMap(login => userStream$) — for each login it creates a fresh user-specific stream. A new login automatically cancels the old one.
  • takeUntil(logout$) — on logout, ends the user-specific inner stream.
  • startWith('anonymous') — sets the initial state BEFORE the first login.

Gotchas

  • mergeMap instead of switchMap — the old user-stream keeps living alongside the new login. One user's private data leaks to another.
  • Resetting only the UI without stopping the upstream — late responses for the old user still arrive and can overwrite the new state.
  • shareReplay caches in a singleton service must be invalidated explicitly on logout. Without that they outlive the logout.

What you get

Logout atomically stops the private streams and returns the app to an anonymous state.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...