我有以下两种方法:
Future<Either<Failure, WorkEntity>> getWorkEntity({int id})
和
Future<Either<Failure, WorkEntity>> updateWorkEntity({int id, DateTime executed})
它们都经过测试,可以按预期工作。然后,我有了结合了两者的第三个方法:
Future<Either<Failure, WorkEntity>> call(Params params) async {
final workEntityEither = await repository.getWorkEntity(id: params.id);
return await workEntityEither.fold((failure) => Left(failure), (workEntity) => repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now()));
}
此方法不起作用,它始终返回null。我怀疑是因为我不知道在fold方法中返回什么。如何使它起作用?
谢谢
索伦
答案 0 :(得分:0)
fold
方法的签名如下:
fold<B>(B ifLeft(L l), B ifRight(R r)) → B
您的ifLeft
“左(失败)”返回一个Either<Failure, WorkEntity>
,但是ifRight
“ repository.updateWorkEntity(id:workEntity.id,已执行:DateTime.now())”是返回Future
。
最简单的解决方案是,如此处所述:How to extract Left or Right easily from Either type in Dart (Dartz)
Future<Either<Failure, WorkEntity>> call(Params params) async {
final workEntityEither = await repository.getWorkEntity(id: params.id);
if (workEntityEither.isRight()) {
// await is not needed here
return repository.updateWorkEntity(id: workEntityEither.getOrElse(null).id, executed: DateTime.now());
}
return Left(workEntityEither);
}
这可能也可行(也未经测试):
return workEntityEither.fold((failure) async => Left(failure), (workEntity) => repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now()));
由于我看不到返回异常有什么好处,所以我将抛出异常并用try/catch
块捕获。