首页 > 解决方案 > 从 Future Either 方法调用两个方法,两者都具有 Future Either 返回类型

问题描述

我有这两种方法:

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。我怀疑这是因为我不知道在折叠方法中返回什么。如何使它起作用?


谢谢索伦_

标签: flutterdart

解决方案


fold方法的签名如下:

fold<B>(B ifLeft(L l), B ifRight(R r)) → B

您的ifLeft“Left(failure)”返回一个Either<Failure, WorkEntity>ifRight“repository.updateWorkEntity(id:workEntity.id,执行:DateTime.now())”返回一个Future

最简单的解决方案是,如下所述:How to extract Left or Right 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块捕获它。


推荐阅读