pakoito
11/26/2019, 11:53 AMIO.parMapN(<http://Dispatchers.IO|Dispatchers.IO>, ioS1, ioS2, ioS3) { a, b, c ->
Either.map(a,b,c) { aa, bb, cc -> ... }
}
Mark Fisher
11/26/2019, 11:54 AMpakoito
11/26/2019, 11:55 AMMark Fisher
11/26/2019, 12:26 PM@Test
fun `io module test`() {
val ioModule = Module(IO.async())
ioModule.run {
val ioS1 = repository.byId(u1).fix().attempt()
val ioS2 = repository.byId(u2).fix().attempt()
val ioS3 = repository.byId(u3).fix().attempt()
val contextIO = IO.dispatchers().io()
val contextS = <http://Schedulers.io|Schedulers.io>().asCoroutineContext()
IO.parMapN(contextS, ioS1, ioS2, ioS3) { a, b, c ->
ioInfo(a)
ioInfo(b)
ioInfo(c)
}.unsafeRunSync()
}
}
Mark Fisher
11/26/2019, 12:26 PMprivate val ioInfo: (Either<Throwable, Int>) -> Unit = { result ->
when (result) {
is Either.Right -> <http://logger.info|logger.info> { "got stock: ${result.b}" }
is Either.Left -> logger.error { "error: ${result.a}" }
}
}
pakoito
11/26/2019, 12:46 PMIO
operationpakoito
11/26/2019, 12:46 PMpakoito
11/26/2019, 12:48 PMfun IO<A>.logError(): IO<A> =
attempt().flatMap {
it.fold(
{ IO { logger.error { "error: $it" } }.flatMap { raiseError(it) } },
{ IO.just(it).flatTap { IO { <http://logger.info|logger.info> { "got stock: $it" } } } }
)
}
and then
val ioS1 = repository.byId(u1).fix().logError()
pakoito
11/26/2019, 12:50 PM<http://logger.info|logger.info>
a suspend functionpakoito
11/26/2019, 12:50 PMMark Fisher
11/26/2019, 12:56 PMMark Fisher
11/26/2019, 2:04 PMEither.map()
I found a map function on applicative(), so could do:
Either.applicative<Throwable>().map(a, b) { (aa, bb) ->
<http://logger.info|logger.info> { "T2 result: $aa, $bb"}
}
but I have to know that only 2 of the results were valid, one wasn't (it was an error). Using the triple version doesn't print anything (i.e. map(a, b, c)
). Is there a way to map over all values without knowing how many were correct?pakoito
11/26/2019, 3:11 PMmap
only works with 3 of thempakoito
11/26/2019, 3:11 PMpakoito
11/26/2019, 3:11 PMpakoito
11/26/2019, 3:11 PMhandleError
, handleErrorWith
or even mapLeft
Mark Fisher
11/26/2019, 4:00 PMEither.applicative<Throwable>().tupled(a, b, c).fix()
which also combines into a left if there's an error too.pakoito
11/26/2019, 5:03 PMEither.map
😄