hi, is there a way to add something to the corouti...
# coroutines
a
hi, is there a way to add something to the coroutine context (say a CoroutineName) whenever a coroutine is launched inside a specific class? for example, in an android ViewModel the viewModelScope is launched. i would like to make it such that the ViewModel could implement some ClassA, where class A's functionality would be to automatically add coroutine context to said coroutine scope
k
Copy code
class CoroutineAndroidViewModel(
  private val scope = CoroutineScope(Job() + CoroutineName("…"))
) : ViewModel {

  override fun onCleared() {
    scope.cancel()
    super.onCleared()
  }
}
a
im not sure i follow.. wouldnt viewModelScope remain unaffected by this?
k
Yes,
viewModelScope
is now discouraged by Google. You should use what I posted above, or you should add a CoroutineScope that implements the
Closeable
interface to the viewmodel. https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycl[…]Main/kotlin/androidx/lifecycle/ViewModel.kt;l=138?q=ViewModel
viewModelScope
tightly couples you to
Dispatchers.Main.immediate
which causes issues, and as you’re experiencing, restricts your ability to universally add custom coroutine context elements to the scope.
a
:ooo this is good intel, thanks
k
I am displeased that Google’s guidance around this isn’t better. Their documentation still mentions using
viewModelScope
i
Uh, no
viewModelScope
is not discouraged - it was just changed to allow overriding it as it is now a constructor parameter: https://developer.android.com/jetpack/androidx/releases/lifecycle#2.8.0
k
I could have sworn you mentioned in a message several months ago it was discouraged
i
Lifecycle 2.8 is not several months old, so the issues that existed back then (the inability to override it or provide an alternative in tests) do not exist anymore, which is why you can write it like this now:
Copy code
class MyViewModel(
  viewModelScope: CoroutineScope = Dispatchers.Main + SupervisorJob() + CoroutineName("yourName")
) : ViewModel(viewModelScope) {
  // Use viewModelScope as before, without any code changes
}
k
Perhaps I misinterpreted!
Screenshot was from July 2023
i
That is precisely why we added the ability to override it in Lifecycle 2.8, yes
Which actually uses this same technique under the hood, it just does all the work for you
k
Any reason these docs don’t mention these facilities in 2.8.0? https://developer.android.com/topic/libraries/architecture/coroutines
i
Do you mind filing a documentation issue for updating that page? We definitely should mention the new stuff there: https://issuetracker.google.com/issues/new?component=192697&template=845603 If you do file an issue, include a link here and I can forward it onto the right person
👍 1
k