Estoy en una situación en la que intento configurar algunos datos y luego llamar a un servicio. Cada paso puede fallar, por lo que estoy tratando de usar Arrow's O para manejar esto.
Pero termino con muchos mapas planos anidados.
El siguiente fragmento de código ilustra lo que estoy tratando de hacer:
import arrow.core.Either import arrow.core.flatMap typealias ErrorResponse = String typealias SuccessResponse = String data class Foo(val userId: Int, val orderId: Int, val otherField: String) data class User(val userId: Int, val username: String) data class Order(val orderId: Int, val otherField: String) interface MyService { fun doSomething(foo: Foo, user: User, order: Order): Either<ErrorResponse, SuccessResponse> { return Either.Right("ok") } } fun parseJson(raw: String): Either<ErrorResponse, Foo> = TODO() fun lookupUser(userId: Int): Either<ErrorResponse, User> = TODO() fun lookupOrder(orderId: Int): Either<ErrorResponse, Order> = TODO() fun start(rawData: String, myService: MyService): Either<ErrorResponse, SuccessResponse> { val foo = parseJson(rawData) val user = foo.flatMap { lookupUser(it.userId) } //I want to lookupOrder only when foo and lookupUser are successful val order = user.flatMap { foo.flatMap { lookupOrder(it.orderId) } } //Only when all 3 are successful, call the service return foo.flatMap { f -> user.flatMap { u -> order.flatMap { o -> myService.doSomething(f, u, o) } } } }Estoy seguro de que hay una mejor manera de hacer esto. ¿Puede alguien ayudarme con un enfoque idiomático?
Puede usar either { } DSL, está disponible en forma suspend o no suspendida a través del constructor either.eager { } .
De esa forma puedes usar suspend fun <E, A> Either<E, A>.bind(): A .
Reescribiendo su ejemplo de código:
fun start(rawData: String, myService: MyService): Either<ErrorResponse, SuccessResponse> = either.eager { val foo = parseJson(rawData).bind() val user = lookupUser(foo.userId).bind() val order = lookupOrder(foo.orderId).bind() myService.doSomething(foo, user, order).bind() } Si te encuentras con un valor de Either.Left , " bind() " cortocircuitará el bloque either.eager y regresará con el valor Either.Left encontrado.