How to extract Left or Right easily from Either type in Dart (Dartz)

三世轮回 提交于 2020-01-25 06:53:28

问题


I am looking to extract a value easily from a method that return a type Either<Exception, Object>.

I am doing some tests but unable to test easily the return of my methods.

For example:

final Either<ServerException, TokenModel> result = await repository.getToken(...);

To test I am able to do that

expect(result, equals(Right(tokenModelExpected))); // => OK

Now how can I retrieve the result directly?

final TokenModel modelRetrieved = Left(result); ==> Not working..

I found that I have to cast like that:

final TokenModel modelRetrieved = (result as Left).value; ==> But I have some linter complain, that telling me that I shouldn't do as to cast on object...

Also I would like to test the exception but it's not working, for example:

expect(result, equals(Left(ServerException()))); // => KO

So I tried this

expect(Left(ServerException()), equals(Left(ServerException()))); // => KO as well, because it says that the instances are different.

回答1:


I can't post a comment... But maybe you could look at this post. It's not the same language, but looks like it's the same behaviour.

Good luck.




回答2:


Ok here the solutions of my problems:

To extract/retrieve the data

final Either<ServerException, TokenModel> result = await repository.getToken(...);
result.fold(
 (exception) => DoWhatYouWantWithException, 
 (tokenModel) => DoWhatYouWantWithModel
);

//Other way to 'extract' the data
if (result.isRight()) {
  final TokenModel tokenModel = result.getOrElse(null);
}

To test the exception

//You can extract it from below, or test it directly with the type
expect(() => result, throwsA(isInstanceOf<ServerException>()));


来源:https://stackoverflow.com/questions/58734044/how-to-extract-left-or-right-easily-from-either-type-in-dart-dartz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!