Ahmed Ibrahim
02/06/2020, 11:35 AMfold
. What I'm doing wrong in my case? and how can I prevent this code from crashing?
class GetStoriesListUseCase @Inject constructor(
private val hackerNewsService: HackerNewsService
) {
suspend fun topStories(
pageNumber: Int,
pageSize: Int = 100
): Either<Throwable, List<StoryUIModel>> =
readTopStoriesIds(pageSize)
.flatMap { getTopStoriesDetails(it) }
.suspended()
private fun getTopStoriesDetails(topStoriesIds: List<Id<Long>>): IO<Throwable, List<StoryUIModel>> =
topStoriesIds.map { it.value() }.parTraverse { anId ->
IO.effect(<http://Dispatchers.IO|Dispatchers.IO>) {
Timber.d("${Thread.currentThread().name}")
hackerNewsService.topStoryDetail(anId).toStoryUIModel()
}
}
private fun readTopStoriesIds(pageSize: Int): IO<Throwable, List<Id<Long>>> =
IO.effect {
hackerNewsService.topStoriesIds().map { Id.just(it) }.take(pageSize)
}
private fun StoryDetails.toStoryUIModel() =
StoryUIModel(id = id, title = title, author = by, url = url)
}
aballano
02/06/2020, 12:11 PMtopStories
function?Ahmed Ibrahim
02/06/2020, 12:12 PMaballano
02/06/2020, 12:12 PMaballano
02/06/2020, 12:12 PMsomeIO.attempt().suspended()
aballano
02/06/2020, 12:16 PMIO<E, A>.attempt(): IO<E, Either<Throwable, A>>
so any fatal failure will be put into the either, but it still allows you to fold over your expected error E and the valueaballano
02/06/2020, 12:17 PMAhmed Ibrahim
02/06/2020, 12:18 PMIO<E, A>
was primarily introduced to replace doing IO work gracefully instead of working with Either?aballano
02/06/2020, 12:20 PMaballano
02/06/2020, 12:20 PMaballano
02/06/2020, 12:22 PMsuspended
) with attempt or you use IO directlyAhmed Ibrahim
02/06/2020, 12:24 PMaballano
02/06/2020, 12:24 PMAhmed Ibrahim
02/06/2020, 12:26 PMattempt().suspended()
in the client code? and catch the exception there through fold
?aballano
02/06/2020, 12:28 PMsuspended
in general, but it really depends on the project and what you want to achieveaballano
02/06/2020, 12:29 PMAhmed Ibrahim
02/06/2020, 12:35 PMIO.catch { } -> IO<Throwable, A>
construct so that it might handle any error that could happen inside that block.aballano
02/06/2020, 12:40 PMIO.effect { }
, IO { }
, etc) is gonna be kept, then you should be able to handle it or not with handleError
, and finally execute it and obtain a value, a domain error or an exceptionAhmed Ibrahim
02/06/2020, 12:54 PMparTraverse
is the best way to go, or there is a better alternative that I should look into?aballano
02/06/2020, 12:57 PM