Skip to content

Instantly share code, notes, and snippets.

@Foxpace
Last active June 5, 2023 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Foxpace/6bc49450015551ba88491b0b21f02a8d to your computer and use it in GitHub Desktop.
Save Foxpace/6bc49450015551ba88491b0b21f02a8d to your computer and use it in GitHub Desktop.
Turbine example viewmodel with multiple states
@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