Hey everyone, I’m looking for the most idiomatic ...
# coroutines
s
Hey everyone, I’m looking for the most idiomatic way to group two “actions” under one cancellable scope (that "inherits" from another scope, read Android's
viewModelScope
) 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:
Copy code
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
a
You can create a job like this:
Copy code
val 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.
a
You can do a flow of filter, and collect latest