繁体   English   中英

用于在 ViewModel 外部实例化的 RoomDatabase 中的 RoomDatabase.Callback() 的协程 scope?

[英]Coroutine scope for a RoomDatabase.Callback() in a RoomDatabase instantiated outside the ViewModel?

我正在使用 Hilt 为 DI 重构我的应用程序,并且在我有一个 ViewModel 实例化 RoomDatabase 以获取 DAO 并将其传递到存储库之前。 .getDatabase 方法有一个 CoroutineScope 参数,用于在 .RoomDatabase.Callback() 内启动协程以异步填充数据库。

class MyViewModel(application: Application) : AndroidViewModel(application) {
    init {
        val dao = MyDB.getDatabase(
            application,
            viewModelScope   //using viewModelScope inside the ViewModel
        ).myDAO()
        repository = MyRepository(dao)
    }
}

abstract class MyDB : RoomDatabase() {

    abstract fun myDAO(): MyDAO

    private class MyDatabaseCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {
...
}

现在使用 Hilt,DB 将在安装在 SingletonComponent 中的模块中实例化:

@Module
@InstallIn(SingletonComponent::class)
object DBModule {
    @Provides
    fun provideDao(@ApplicationContext applicationContext: Context) : MyDAO {
        return MyDB.getDatabase(
            applicationContext,
            scope         // What CoroutineScope to use here ???
        ).myDAO
    }

    @Provides
    fun provideRepository(dao: MyDAO) = MyRepository(dao)
}

在这种情况下,最好的 scope 是什么,因为 viewModelScope 不能再使用了? 以及如何引用它? 理想情况下是一个 ActivityRetained 范围的,因此它的范围不限于整个应用程序,但它会在 Activity 重新启动(即配置更改等)后继续存在

先感谢您。

我希望它对您的用例有所帮助。

    // You will have to use hilt with viewModel as well in order to used below function further more I don't recomment to used that as
    // ViewModelScop strick inside viewModel. If It comes to database then It should not restrict to viewModel Infact database is a component which 
    // Provide service to each part of the application so use Simple Coroutine scope... 
    // Incase something goes wrong and your activity kills/destoryed then the opertaion get stoped because of viewModelScope
    @Provides
    fun provideCorountineScope(viewModel: MyViewModel): CoroutineScope {
        return viewModel.viewModelScope
    }

    @Singleton
    @Provides
    fun providesCoroutineScope(): CoroutineScope {
        // Run this code when providing an instance of CoroutineScope
        return CoroutineScope(SupervisorJob() + Dispatchers.IO)
    }

    @Singleton
    @Provides
    fun provideDao(@ApplicationContext applicationContext: Context, scope: CoroutineScope) : MyDAO {
        return MyDB.getDatabase(
            applicationContext,
            scope
        ).myDAO
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM