Created
March 7, 2022 20:46
-
-
Save MessiasLima/6d3ee3d14ed9bdfc29ebb862eb74bb3d to your computer and use it in GitHub Desktop.
Retryable Flow implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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