What is the recommended way to handle periodic cal...
# android
z
What is the recommended way to handle periodic calls in ViewModels and cancel them after navigating to a different screen? say I have a ViewModel:
Copy code
@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:
Copy code
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:
Copy code
@Composable
fun SomeScreen(
    viewModel: SomeViewModel = hiltViewModel(),
) { ... }
p
I have been using this way for some years now, and it works really well.
d
Looks ok