Last active
June 5, 2023 17:18
-
-
Save Foxpace/6bc49450015551ba88491b0b21f02a8d to your computer and use it in GitHub Desktop.
Turbine example viewmodel with multiple states
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
@HiltViewModel | |
class ExampleViewModel @Inject constructor( | |
private val computationRepo: HeavyComputationTemplate, | |
) : ViewModel() { | |
private val _vmState: MutableStateFlow<VmState> = MutableStateFlow(VmState.Waiting) | |
val vmState = _vmState.asStateFlow() | |
// duplicate StateFlow to track | |
private val _secondVmState: MutableStateFlow<VmState> = MutableStateFlow(VmState.Waiting) | |
val secondVmState = _secondVmState.asStateFlow() | |
fun onEvent(event: VmEvents): Job = when (event) { | |
VmEvents.OnLaunch -> onLaunch() | |
} | |
private fun onLaunch() = viewModelScope.launch(Dispatchers.Main) { | |
// running the jobs asynchronously | |
awaitAll( | |
async { processFirstTask() }, | |
async { processSecondTask() } | |
) | |
} | |
private suspend fun processFirstTask() { | |
_vmState.value = VmState.Running | |
val result = computationRepo.doComputation() | |
_vmState.value = VmState.Finished(result) | |
_vmState.value = VmState.Waiting | |
} | |
private suspend fun processSecondTask() { | |
_secondVmState.value = VmState.Running | |
val result = computationRepo.doComputation() | |
_secondVmState.value = VmState.Finished(result) | |
_secondVmState.value = VmState.Waiting | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment