Skip to content

Instantly share code, notes, and snippets.

@IkariMeister
Last active April 1, 2019 20:13
Show Gist options
  • Save IkariMeister/203dfd5af63eb0207478207453802ce8 to your computer and use it in GitHub Desktop.
Save IkariMeister/203dfd5af63eb0207478207453802ce8 to your computer and use it in GitHub Desktop.
suspend fun getCards() =
service.getCards()
.async(IO.async())
.fix()
.map { response ->
when (response.code()) {
200 -> response.body()?.cards?.right() ?: NoContent.left()
204 -> NoContent.left()
404 -> NoInternetConnection.left()
401 -> NotAllowedError.left()
403 -> NotAllowedError.left()
500 -> UnexpectedError.left()
else -> UnidentifiedError.left()
}
}
operator fun invoke() = fx {
val (api, local) = !NonBlocking.parMapN(
effect {
apiClient.getCards().map { result ->
result.bimap({ it.toModel() },
{ cards ->
cards.mapNotNull { it.toModel() }
}
)
}
}.flatten()
,
effect { dao.getCards().map { it.toModel() }.right() },
::Tuple2
)
effect {
api.map { cards ->
cards.map {
dao.insertCard(it.toDb())
}
}
}
api.takeIf { it.isRight() }?.let { api.combineK(local) } ?: local
}
fun loadCards() =
unsafe {
view?.showLoading()
getCards().unsafeRunSync()
}
.fold(
{ error ->
view?.hideLoading()
view?.showEmptyCase(error)
},
{ cards ->
view?.hideLoading()
view?.showItems(cards)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment