使用Hilt在Application中注入IO调度器,规避GlobalScope
解决方案
要避免使用GlobalScope并改用IO调度器,你可以通过Hilt注入一个与Application生命周期绑定的专用CoroutineScope,具体步骤如下:
1. 新增Application级Scope的限定符(可选但更规范)
添加一个自定义Qualifier,用于区分Application专用的CoroutineScope,避免与其他Scope冲突:
import javax.inject.Qualifier @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope
2. 修改CoroutineScope提供模块
调整CoroutinesScopesModule,提供一个绑定IO调度器的Application级CoroutineScope:
import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob @Module @InstallIn(SingletonComponent::class) object CoroutinesScopesModule { @ApplicationScope @Provides fun providesApplicationCoroutineScope( @IoDispatcher ioDispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + ioDispatcher) }
SupervisorJob确保单个协程失败不会影响Scope内其他协程,适合Application级别的后台操作- 直接绑定
@IoDispatcher,后续使用时无需额外指定调度器
3. 改造Application类
注入上述自定义Scope,替换GlobalScope:
import android.app.Application import dagger.hilt.android.HiltAndroidApp import com.example.data.feature.common.preference.PreferenceRepository import javax.inject.Inject import kotlinx.coroutines.CoroutineScope @HiltAndroidApp class MainApplication : Application() { @Inject lateinit var preferenceRepository: PreferenceRepository @Inject @ApplicationScope lateinit var applicationScope: CoroutineScope override fun onCreate() { super.onCreate() resetPreference() } fun resetPreference() { applicationScope.launch { preferenceRepository.putManagerInfo("") } } }
核心优势
- 完全替代
GlobalScope,避免其生命周期不明确、无法管控的问题 - 专用Scope与Application生命周期绑定,不会出现内存泄漏
- 直接使用IO调度器执行偏好设置操作,符合数据持久化操作的线程要求
内容的提问来源于stack exchange,提问作者c-an
相关产品推荐
相关产品推荐

