Created
August 6, 2023 12:43
-
-
Save fstanis/3ac914bc462f84459f746988066eb520 to your computer and use it in GitHub Desktop.
Hilt inject a CoroutineScope into anything @ViewModelScoped
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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