-
Notifications
You must be signed in to change notification settings - Fork 5
CallResult
A CallResult<L, R> represents a value of two possible types, a Failure or a Success. This simply means that you have either a left or a right member, but never both at the same time. This class is present in JCoinbase since version 0.0.1.
Please note that CallResult, is a simplified version of the vavr
Either
and provide you a powerful API based on lambdas. Thus, you are not dependent on vavr if you do not wish to use it. x
For example, if a method returns a CallResult<Seq<CoinbaseError>, User>
, then you will either have a
Seq
of CoinbaseError
or a User
. Then you can access the left or the right member using the CallResult API.
CallResult<Seq<CoinbaseError>, User> currentUser = client.user().getCurrentUser();
//Get the user. Throws exception if this is a failure
currentUser.get();
//Get the user or return null if this is a failure
currentUser.getOrNull();
//Get the user or return the given user if this is a failure
currentUser.getOrElse(User.builder()[...].build());
//Get the user or execute myInstruction() if this is a failure
currentUser.getOrElse(() -> myInstruction());
//Get the user or throws a new exception if this is a failure
currentUser.getOrElseThrow(() -> new RuntimeException())
//Get the underlying user or the result of Try.of(theSupplier).get()
currentUser.getOrElseTry(OneClass::methodToInvoke);
//Get the underlying left member. Throws exception if this is a Success.
currentUser.getFailure();
In this example, if this is a failure, client.user().getCurrentUser()
will return a CallResult.Failure
,
otherwise it will return a CallResult.Success
.
Now, imagine that we want to map the underlying user to another thing
//This method maps the value of this CallResult if it is a Success and performs no operation if this is a Failure.
currentUser.map(User::getId);
Note that the map is also available for the Failure side of a CallResult using
mapFailure()``
//Transform the CoinbaseErrors to a list of messages if this is a failure. Do nothing otherwise.
currentUser.mapFailure(coinbaseErrors -> coinbaseErrors.map(CoinbaseError::getMessage));
CallResult also gives you access to useful methods like:
//Return true if this is a success, false otherwise
currentUser.isSuccess();
//Return true if this is a failure, false otherwise
currentUser.isFailure();
//Return true if this a success with an underlying value, false otherwise
currentUser.isEmpty();
Many other methods are available in the CallResult api, like peek()
, peekFailure()
, bimap()
, flatMap()
, orElse()
, fold()
, toOption()
, toJavaOptional()
...
For more information on the CallResult
class you can also check the javadoc
© 2021 Alexis "Bad_Pop" Vachard. All Rights Reserved
Website | Sonar Qube | Javadoc | Jacoco reports | Maven reports