【发布时间】:2021-06-08 06:20:04
【问题描述】:
我有两个异步函数调用外部系统返回 Either
suspend fun getAs(): Either<Exception, List<A>> = TODO()
suspend fun getBs(): Either<Exception, List<B>> = TODO()
suspend fun doSomethingWithA(listA: List<A>): Unit = TODO()
launch {
val deferredA = async { getAs() }
val deferredB = async { getBs() }
either<Exception, List<A>> {
val listOfAs = deferredA.await()
.bimap(leftOperation = { e ->
println("special message on error for A")
e
}, rightOperation = { listA ->
doSomethingWithA(listA)
listA
})
.bind()
val listOfBs = deferredB.await().bind()
listOfAs.filter { it.someId !in listOfBs.map { it.someProperty } }
}
.map { /* handle result */ }
.handleError { /* handle error */ }
}
另一种选择是像这样使用map{} 函数
launch {
val deferredA = async { getAs() }
val deferredB = async { getBs() }
deferredA.await()
.bimap(leftOperation = { e ->
println("special message on error for A")
e
}, rightOperation = { listA ->
doSomethingWithA(listA)
deferredB.await().map { listB ->
listA.filter { a -> a.someId !in listB.map { it.someProperty } }
}
})
.map { /* handle result */ }
.handleError { /* handle error */ }
}
【问题讨论】:
标签: kotlin async-await either arrow-kt