我创造了这样的东西。
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作用域。
1条答案
按热度按时间wlp8pajw1#
您可以将
ProcessLifecycleOwner
用于进程的lifecycle
和lifecycScope
。https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner您需要将以下依赖项与其他生命周期依赖项一起添加-
注射你的调度员-