Last active
June 5, 2023 17:16
-
-
Save Foxpace/97df0f6e7dff002659917b11f5c91809 to your computer and use it in GitHub Desktop.
Example viewmodel for examples on turbine
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
// interface for heavy computation job, which returns the string | |
interface HeavyComputationTemplate { | |
suspend fun doComputation(): String | |
} | |
// Hilt annotations are not needed in the example | |
// because we will manually inject mocks - in real app with hilt, they are essential | |
@HiltViewModel | |
class ExampleViewModel @Inject constructor( | |
private val computationRepo: HeavyComputationTemplate, | |
) : ViewModel() { | |
private val _vmState: MutableStateFlow<VmState> = MutableStateFlow(VmState.Waiting) | |
val vmState = _vmState.asStateFlow() | |
fun onEvent(event: VmEvents): Job = when (event) { | |
VmEvents.OnLaunch -> onLaunch() | |
} | |
private fun onLaunch() = viewModelScope.launch(Dispatchers.Main) { | |
_vmState.value = VmState.Running | |
val result = computationRepo.doComputation() | |
_vmState.value = VmState.Finished(result) | |
_vmState.value = VmState.Waiting | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment