Zan Skamljic
07/06/2023, 1:24 PM@HiltViewModel
class SomeViewModel @Inject constructor(
private val someUseCase: SomeUseCase,
) : ViewModel() {
private var periodicJob: Job? = null
fun startPeriodic() {
periodicJob?.cancel()
periodicJob = viewModelScope.launch {
while (true) {
someUseCase()
delay(1000)
}
}
}
fun endPeriodic() {
periodicJob?.cancel()
}
}
And then in the composable I do:
DisposableEffect(viewModel) {
viewModel.startPolling()
onDispose {
viewModel.endPolling()
}
}
Is this the correct way? I've also tried simply launching the while loop in ViewModel's init, but that was never stopped. ViewModel is passed as parameter as following:
@Composable
fun SomeScreen(
viewModel: SomeViewModel = hiltViewModel(),
) { ... }
Parthasarathy
07/06/2023, 7:23 PMDzmitry
07/07/2023, 5:57 AM