antoniomarin
01/31/2020, 2:13 PMUseCase
, I guess flow
should be used?streetsofboston
01/31/2020, 2:13 PMantoniomarin
01/31/2020, 2:14 PMstreetsofboston
01/31/2020, 2:14 PMsuspend fun …
antoniomarin
01/31/2020, 2:14 PMstreetsofboston
01/31/2020, 2:15 PMstreetsofboston
01/31/2020, 2:16 PMclass UseCase {
suspend fun getDataFromNetwork(input: Data): Response {
val request1Result = repo.getResult1(input.field1)
val request2Result = repo2.getResult2(input.field2)
return combineResults(request1Result, request2Result)
}
...
}
antoniomarin
01/31/2020, 2:21 PMstreetsofboston
01/31/2020, 2:22 PMsuspend fun buildUseCase(params: None) : CharSequence {
val clientId = sessionRepository.getLoggedInClientId()
return try {
val content = contentsRepository.getHtmlContent(CONTENT_NAME, clientId)
content.contentValue.toHtml()
} catch (error: Throwable) {
contentsRepository.getHtmlContent(CONTENT_NAME, DEFAULT_CLIENT_ID)
}
}
streetsofboston
01/31/2020, 2:36 PMSingle<T>
to a Flow<T>
, in case you can’t change the function/method signatures of your repos, take a look at this:
https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive/kotlinx-coroutines-rx2antoniomarin
01/31/2020, 2:56 PMoverride fun buildUseCase(params: None): Single<CharSequence> {
return sessionRepository.getLoggedInClientId()
.flatMap { clientId -> contentsRepository.getHtmlContent(CONTENT_NAME, clientId) }
.onErrorResumeNext(contentsRepository.getHtmlContent(CONTENT_NAME, DEFAULT_CLIENT_ID))
}
Thanks for helping, one question tho, how to handle error for second api which is in catch block. Does that means I would need to add other try
block inside existing one?
I’m trying to figure out are there more elegant solutions 😄streetsofboston
01/31/2020, 4:39 PMgetHtmlContent
is part of the onErrorResumeNext. If that second call emits an exception/throwable, the final Single returned by buildUseCase will emit that exception as well.
The same will happen in the suspend fun buildUseCase
snippet as well: If the second call to getHtmlContext
throws an exception, the suspend fun buildUseCase
will throw an exception.
Your Rx example and the corresponding suspend
example are behaving in similar ways.streetsofboston
01/31/2020, 4:43 PMrunCatching
block followed by a .mapCatching
block, which allows you to avoid nested try-catch clauses .antoniomarin
01/31/2020, 5:00 PMflow
, going flowOf(api1, api2)
and then doing some kind of reactive flow?
Sorry if I’m making nonsenses 😄streetsofboston
01/31/2020, 6:11 PMantoniomarin
02/03/2020, 10:23 AMtry {
val result = runCatching {
repository.api(params1)
}.getOrElse {
repository.api(params2)
}
handleSuccess(result)
catch(exp: Exception) {
handleError(exp)
}