Skip to content

Instantly share code, notes, and snippets.

@Foxpace
Last active June 5, 2023 17:16
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/97df0f6e7dff002659917b11f5c91809 to your computer and use it in GitHub Desktop.
Save Foxpace/97df0f6e7dff002659917b11f5c91809 to your computer and use it in GitHub Desktop.
Example viewmodel for examples on turbine
// 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