Stanislav Kral
05/15/2025, 9:04 AMviewModelScope
) so that I can wipe all in-flight work whenever my filter changes—rather than cancelling each Job?
by hand.
Here’s what I’ve got today:
class MyViewModel : ViewModel() {
private var loadNextPageJob: Job? = null
private var refreshJob: Job? = null
fun onLoadNextPage() {
loadNextPageJob = viewModelScope.launch {
// …fetch next page, show retry SnackBar, recurse on retry…
}
}
fun onRefresh() {
refreshJob = viewModelScope.launch {
// …fetch fresh data, toggle spinner, show error SnackBar…
}
}
fun setFilter(filter: Filter) {
// I want to cancel *all* running work here…
loadNextPageJob?.cancel()
refreshJob?.cancel()
// …then apply the new filter
}
}
I thought of creating a custom scope, but I am not sure how to properly "inherit" from viewModelScope
Albert Chang
05/15/2025, 3:35 PMval job = Job(parent = viewModelScope.coroutineContext[Job])
and use viewModelScope.launch(job) {}
so that all the launched jobs are the children of the job you created and calling job.cancel()
will cancel all the children.Alexandru Caraus
05/18/2025, 9:15 AM