Last active
August 25, 2023 14:42
-
-
Save mutkuensert/11093b3c8b48fa130b0b35bcb5e9faf1 to your computer and use it in GitHub Desktop.
An helper class for mutkuensert/Android-Phase
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 com.github.michaelbull.result.Result | |
import com.github.michaelbull.result.onFailure | |
import com.github.michaelbull.result.onSuccess | |
import com.mutkuensert.androidphase.Phase | |
import kotlinx.coroutines.coroutineScope | |
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.flow.StateFlow | |
import kotlinx.coroutines.flow.asStateFlow | |
import kotlinx.coroutines.launch | |
class GetPhaseFlow { | |
companion object { | |
suspend fun <T : Any, R : Throwable> execute(block: suspend () -> Result<T, R>): StateFlow<Phase<T>> = | |
coroutineScope { | |
val phase = MutableStateFlow<Phase<T>>(Phase.Standby()) | |
launch { runBlock(phase = phase, block = block) } | |
phase.asStateFlow() | |
} | |
private suspend fun <T : Any, R : Throwable> runBlock( | |
phase: MutableStateFlow<Phase<T>>, | |
block: suspend () -> Result<T, R> | |
) { | |
phase.value = Phase.Loading() | |
block.invoke().onSuccess { | |
phase.value = Phase.Success(data = it) | |
} | |
.onFailure { | |
phase.value = Phase.Error(error = it, message = it.message) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment