Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling two methods from a Future Either method, both with Future Either return type

Tags:

flutter

dart

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

like image 209
Neigaard Avatar asked Sep 19 '25 13:09

Neigaard


1 Answers

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.

like image 180
Dimitri L. Avatar answered Sep 21 '25 03:09

Dimitri L.