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
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.
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.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
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