【问题标题】:Calling two methods from a Future Either method, both with Future Either return type从 Future Either 方法调用两个方法,两者都具有 Future Either 返回类型
【发布时间】:2019-12-30 21:17:20
【问题描述】:

我有这两种方法:

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

谢谢
索伦

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    fold 方法的签名如下:

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

    您的 ifLeft "Left(failure)" 返回 Either&lt;Failure, WorkEntity&gt;ifRight "repository.updateWorkEntity(id: workEntity.id, executed: 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 块捕获它。

    【讨论】:

    • 首先,我从“return Left(workEntityEither); ”。第二个班轮返回 null。
    • 其实它是有效的,是在测试时很累......对不起
    • 你是指第一个解决方案还是第二个解决方案?
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2015-01-05
    • 2021-10-20
    • 2019-08-12
    • 2021-01-18
    • 2020-11-17
    相关资源
    最近更新 更多