withValidToken<R> method
Runs operation with a valid token, retrying once if the operation
returns a 401-coded failure (Failure.unauthorized or any
failure.code == 401).
The retry is bounded to a single additional attempt to avoid loops; if the second call also fails, that failure is returned to the caller.
Implementation
Future<Result<R>> withValidToken<R>(
Future<Result<R>> Function(Token token) operation,
) async {
_checkNotDisposed();
final initial = await getValidToken();
if (initial is Error<Token>) return Error<R>(initial.failure);
final firstToken = (initial as Success<Token>).data;
final firstAttempt = await operation(firstToken);
if (firstAttempt is! Error<R>) return firstAttempt;
if (firstAttempt.failure.code != 401) return firstAttempt;
_log(LogLevel.debug, 'operation returned 401; refreshing and retrying');
final refreshed = await forceRefresh();
if (refreshed is Error<Token>) return Error<R>(refreshed.failure);
return operation((refreshed as Success<Token>).data);
}