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.
Either<int, String> response = Right("Hello, im right"); This is how simple it is to use Either(), you declare the Left and Right type inside the generic type parameters in the respective order. To assign value use Left(value) or Right(value) .
Functional programming in Dart and Flutter. All the main functional programming types and patterns fully documented, tested, and with examples. Fpdart is fully documented. You do not need to have any previous experience with functional programming to start using fpdart .
A function (also might be referenced to as method in the context of an object) is a subset of an algorithm that is logically separated and reusable. It can return nothing (void) or return either a built-in data type or a custom data type. It can also have no parameters or any number of parameters.
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>()));
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.
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