Skip to content

Instantly share code, notes, and snippets.

@fstanis
Created August 6, 2023 12:43
Show Gist options
  • Save fstanis/3ac914bc462f84459f746988066eb520 to your computer and use it in GitHub Desktop.
Save fstanis/3ac914bc462f84459f746988066eb520 to your computer and use it in GitHub Desktop.
Hilt inject a CoroutineScope into anything @ViewModelScoped
// Copyright 2023 Google LLC.
// SPDX-License-Identifier: Apache-2.0
import dagger.hilt.android.ViewModelLifecycle
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
@ViewModelScoped
class ViewModelScope @Inject constructor(viewModelLifecycle: ViewModelLifecycle) : CoroutineScope {
override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate
init {
viewModelLifecycle.addOnClearedListener {
coroutineContext.cancel()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment