[英]With dartz is it possible to pass a failure on to the function that is folding my either
我有以下代碼
class GetAuthUserUseCase {
final AuthRepository _authRepository;
GetAuthUserUseCase({
required AuthRepository authRepository,
}) : _authRepository = authRepository;
Future<Either<Failure, AuthUser>> call() async {
final userResponse = await _authRepository.getUser();
var user = userResponse.fold(
(Failure l) => //How can I return the failure from the call function?,
(AuthUser r) => r,
);
final accessTokenExpiresAtMilliseconds =
user.accessTokenIssuedAtMilliseconds + user.accessTokenExpiresInMilliseconds;
final accessTokenExpiresAtDateTime =
DateTime.fromMillisecondsSinceEpoch(accessTokenExpiresAtMilliseconds);
if (DateTime.now().isBefore(accessTokenExpiresAtDateTime)) {
return userResponse;
}
return _authRepository.refreshUser(
user: user,
);
}
}
在我的用例中,我有一些業務邏輯來確定我是否需要刷新用戶訪問令牌。 基於此,我刷新了我的用戶。 但是我需要先使用getUser()
加載我的用戶,以確定訪問令牌是否已過期。
getUser()
將返回一個Either<Failure,AuthUser>
所以我折疊它來獲取用戶。 但我想要的是傳播失敗,以便它終止調用方法並從調用方法輸出失敗。
如果可能的話,我想避免對 Failure 或 AuthUser 進行類型檢查,因為我認為這會使我的程序不那么健壯。
這可能嗎?
對於這種情況,您可以使用isLeft()
來檢查失敗。 和isRight()
成功。
Future<Either<Failure, AuthUser>> call() async {
final userResponse = await _authRepository.getUser();
if(userResponse.isLeft()){
// do your stuffs
}
在這里面,你可能想直接訪問數據,這個擴展會有所幫助
extension EitherX<L, R> on Either<L, R> {
R asRight() => (this as Right).value; //
L asLeft() => (this as Left).value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.