我正在使用 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)
}
在這種情況下使用的最佳范圍是什么,因為 viewModelScope 不能再使用了?以及如何參考它?理想情況下,一個 ActivityRetained 范圍是一個,所以它不是整個應用程式的范圍,但它會在 Activity 重新啟動(即配置更改等)后繼續存在
先感謝您。
uj5u.com熱心網友回復:
我希望它對您的用例有所幫助。
// 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383403.html
標籤:安卓 科特林 android-room kotlin 协程 匕首柄
