Gopal S Akshintala
08/22/2020, 8:39 AMeither{} DSL. The return type of this is Either<E,A> , so I understand one way the composition trips to left is -- one of the functions inside returns an either in left
I am unable to figure out how to explicitly return an either in left from within the block.
For example:
val result: Either<String, String> = either { // This casts the side-effect function into a suspend function.
val id = !getSomethingFromDb(true)
val data = !getSomethingElseFromNetwork(id)
val either = if (data.isEmpty()) {
// vvv how to return either on left
!"SOME_CUSTOM_ERROR".raiseError()
} else data.right()
either
}
I understand for a case like this where I have this requirement on the last step, I can return from outside the block, but just curious how to short-circuit from the middle of the block?Gopal S Akshintala
08/22/2020, 10:42 AMdata in my example) is on right state, but based on it's value, I have to return a custom error so that the output of either{} block is on CUSTOM_ERROR.left()Gopal S Akshintala
08/22/2020, 11:04 AM@Test
fun `either fx`() = runBlocking {
val result: Either<String, String> = either { // This casts the side-effect function into a suspend function.
val id = !getSomethingFromDb(true)
val data = !getSomethingElseFromNetwork(id)
!(if (data.isEmpty()) "CUSTOM_ERROR".left() else data.right())
}
println(result)
}stojan
08/22/2020, 11:25 AMval dataEither = getSomethingElseFromNetwork(id)
!dataEither.filterOrElse({!it.isEmpty()}, {CustomError})stojan
08/22/2020, 11:26 AMeither block, you need an Either.Left and you have to bind on it 🙂Gopal S Akshintala
08/22/2020, 11:26 AMstojan
08/22/2020, 11:26 AMGopal S Akshintala
08/22/2020, 11:27 AMGopal S Akshintala
08/22/2020, 11:27 AMstojan
08/22/2020, 11:31 AMeither block is sugar for map and flatMapstojan
08/22/2020, 11:32 AMbind() it's flatMapGopal S Akshintala
08/22/2020, 11:34 AMfilterOrElse can be said consistent in this style, as this comprehension is all about eliminating only the noise of flatMapGopal S Akshintala
08/22/2020, 11:36 AMval validate2Throwable: Validator<Egg, ValidationFailure> = {
// Awesome DSL from arrow to work with either in an imperative way (Best of both worlds).
either<ValidationFailure, Boolean> { // This casts the side-effect function into a suspend function.
throwableRule2(it)
}.filterOrElse(::identity) { TOO_LATE_TO_HATCH_2 }
}