android 使用hilt在Application中注入io调度器

wfsdck30  于 2023-03-27  发布在  Android
关注(0)|答案(1)|浏览(184)

我创造了这样的东西。

import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import com.example.data.feature.common.preference.PreferenceRepository
import javax.inject.Inject
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@HiltAndroidApp
class MainApplication : Application() {
    @Inject lateinit var preferenceRepository: PreferenceRepository

    override fun onCreate() {
        super.onCreate()
        resetPreference()
    }

    fun resetPreference() = GlobalScope.launch{
        preferenceRepository.putManagerInfo("")
    }
}
import javax.inject.Qualifier

@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher

@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher

@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MainDispatcher

@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class MainImmediateDispatcher
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 {
    @Provides
    fun providesCoroutineScope(
        @DefaultDispatcher defaultDispatcher: CoroutineDispatcher
    ): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher)
}
@Module
@InstallIn(SingletonComponent::class)
object CoroutinesDispatchersModule {
    @DefaultDispatcher
    @Provides
    fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default

    @IoDispatcher
    @Provides
    fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO

    @MainDispatcher
    @Provides
    fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main

    @MainImmediateDispatcher
    @Provides
    fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
}

但是我想避免在Application类中使用GlobalScope。我该如何解决这个问题呢?我需要使用IO作用域。

wlp8pajw

wlp8pajw1#

您可以将ProcessLifecycleOwner用于进程的lifecyclelifecycScopehttps://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

ProcessLifecycleOwner.get().lifecycleScope.launch([YOUR_DISPATCHER_HERE]) {
  //task
}

您需要将以下依赖项与其他生命周期依赖项一起添加-

implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version")

注射你的调度员-

@IoDispatcher
@Inject lateinit var ioDispacher: CoroutineDispatcher

相关问题