Skip to content

Instantly share code, notes, and snippets.

@MessiasLima
Created March 7, 2022 20:46
Show Gist options
  • Save MessiasLima/6d3ee3d14ed9bdfc29ebb862eb74bb3d to your computer and use it in GitHub Desktop.
Save MessiasLima/6d3ee3d14ed9bdfc29ebb862eb74bb3d to your computer and use it in GitHub Desktop.
Retryable Flow implementation
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.onEach
@FlowPreview
fun <T> retryableFlow(retryTrigger: RetryTrigger, flowProvider: () -> Flow<T>) =
retryTrigger.retryEvent.filter { it == RetryTrigger.State.RETRYING }
.flatMapConcat { flowProvider() }
.onEach { retryTrigger.retryEvent.value = RetryTrigger.State.IDLE }
class RetryTrigger {
enum class State { RETRYING, IDLE }
val retryEvent = MutableStateFlow(State.RETRYING)
fun retry() {
retryEvent.value = State.RETRYING
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment