I have these two methods:
Future<Either<Failure, WorkEntity>> getWorkEntity({int id})
and
Future<Either<Failure, WorkEntity>> updateWorkEntity({int id, DateTime executed})
They are both tested and work as expected. I then have this third method that combines the two:
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()));
}
This method does not work, it always return null. I suspect it is because I do not know what to return in the fold methods. How can this be made to work?
Thank you
Søren
The signature for the fold
method is as follows:
fold<B>(B ifLeft(L l), B ifRight(R r)) → B
your ifLeft
"Left(failure)" is returning an Either<Failure, WorkEntity>
but ifRight
"repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now())" is returning a Future
.
The easiest solution would be, as described here: 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);
}
Also this might work (also untested):
return workEntityEither.fold((failure) async => Left(failure), (workEntity) => repository.updateWorkEntity(id: workEntity.id, executed: DateTime.now()));
Since I can not see any benefit in returning an exception I would just throw the exception and catch it with a try/catch
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With