AmrJyniat
06/30/2022, 1:18 PMSharedFlow
when the first collect got exception?
like I expose a Flow
from repo to VM then convert it to SharedFlow
by shareIn()
then collect this SharedFlow from the fragment, now I got an exception while collecting the SharedFlow, so how to retry/recollect it again?gildor
07/05/2022, 4:14 AMretry
for this:
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/retry.htmlgildor
07/05/2022, 4:17 AMretry
gildor
07/05/2022, 4:22 AMAmrJyniat
07/05/2022, 7:07 AMflow.retryWhen { cause, attempt ->
attempt < 3
}
But I have a button for retrying the API call when failed and, I couldn't handle the retry mechanism when the click event occurred.gildor
07/05/2022, 7:10 AMgildor
07/05/2022, 7:12 AMgildor
07/05/2022, 7:12 AMgildor
07/05/2022, 7:12 AMAmrJyniat
07/05/2022, 7:20 AMval flow: Flow<Result<T>> = repo.getData()
And collect the flow in the fragment, now the retry button appears when the result
failed, I searched for an elegant/clean way to recollect the flow on the click event, therefore, the API called again but I didn't found.
I ended up with something like that:
private val _sponsors = Channel<Unit>()
val sponsors = _sponsors.receiveAsFlow().flatMapLatest {
repository.loadSponsors()
}.myShareIn(viewModelScope, replay = 1)
fun loadSponsors() = viewModelScope.launch {
_sponsors.send(Unit)
}
init { loadSponsors() }
In this case, just call `loadSponsors()`fun when the retry button clicked, what do you think?gildor
07/05/2022, 9:33 AMgildor
07/05/2022, 9:33 AMgildor
07/05/2022, 9:34 AMgildor
07/05/2022, 9:34 AMgildor
07/05/2022, 9:36 AMval sponsors = _sponsors.receiveAsFlow().flatMapLatest {
return runCatching {
repository.loadSponsors())
}
}.myShareIn(viewModelScope, replay = 1)
gildor
07/05/2022, 9:36 AMAmrJyniat
07/05/2022, 9:40 AMgildor
07/05/2022, 9:47 AMAmrJyniat
07/05/2022, 10:10 AMsponsors
val is a flow containing custom Result class Result<T>
, so when collecting it in the fragment I'm just checking if the result failed or not, therefore, I don't need any processing in the VM like runCathing{}
because the catch applied already in the repo layer.gildor
07/05/2022, 12:51 PMAmrJyniat
07/05/2022, 12:58 PMgildor
07/05/2022, 1:51 PMgildor
07/05/2022, 1:52 PMgildor
07/05/2022, 1:53 PMAmrJyniat
07/05/2022, 2:03 PMgildor
07/05/2022, 3:09 PM