TokenKeeper class

Coordinates access-token retrieval, proactive refresh, single-flight refresh, and authenticated operation retry — built on top of resilify so failure handling is unified with the rest of your networking stack.

Guarantees:

  • exactly one refresh runs at a time, even under 50+ concurrent calls,
  • no method on the public surface throws,
  • lifecycle events are observable through events and tokenStream.

Constructors

TokenKeeper({required TokenStorage storage, required TokenRefresher refresher, Duration proactiveWindow = Duration.zero, Clock clock = const Clock(), RefreshRetryConfig retryConfig = const RefreshRetryConfig(), TokenKeeperLogger logger = noopLogger})
Creates a keeper.

Properties

events Stream<TokenEvent>
Lifecycle events. Use this to drive logout flows or UI feedback.
no setter
hashCode int
The hash code for this object.
no setterinherited
isRefreshing bool
true while a refresh call is actively in flight.
no setter
lastRefreshAt DateTime?
The timestamp of the most recent successful refresh, or null if no refresh has completed in this keeper's lifetime.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
tokenStream Stream<Token?>
Reactive stream of token changes.
no setter

Methods

clear() Future<void>
Wipes stored credentials and emits TokenClearedEvent.
currentTokenStream() Stream<Token?>
Returns a Stream that immediately emits the current stored token and then continues with every subsequent change from tokenStream.
dispose() Future<void>
Closes event streams and releases internal state.
forceRefresh() Future<Result<Token>>
Forces a refresh, regardless of expiry.
getValidToken() Future<Result<Token>>
Returns a token that is currently valid, refreshing if needed.
hasValidToken() Future<bool>
Returns true if a non-expired token exists in storage.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onEvent<T extends TokenEvent>() Stream<T>
Returns a typed stream of TokenEvents filtered to events of type T.
peek() Future<Token?>
Returns the stored token without touching the network.
refreshIfNeeded() Future<Result<Token>>
Alias for getValidToken with a name that reads more naturally at call sites that don't immediately consume the returned token (e.g. background warmups or pre-flight checks).
setTokens(Token token) Future<void>
Persists token. Emits TokenRefreshedEvent.
toString() String
A string representation of this object.
inherited
withValidToken<R>(Future<Result<R>> operation(Token token)) Future<Result<R>>
Runs operation with a valid token, retrying once if the operation returns a 401-coded failure (Failure.unauthorized or any failure.code == 401).

Operators

operator ==(Object other) bool
The equality operator.
inherited