[英]Get ViewModel's coroutine scope with Hilt
假設,我的 ViewModel class 在其構造函數中有一些 UseCase。 另一方面,這個 UseCase 在其構造函數中有一個 CoroutineScope。 我想使用 viewModelScope 作為參數。 我可以用 Hilt 做嗎?
@InstallIn(ViewModelComponent::class)
abstract class ViewModelModule {
@Provides
fun provideUseCase(scope: CoroutineScope) = MyUseCase(scope)
}
...
@HiltViewModel
class MyViewMode(useCase: MyUseCase): ViewModel() {
...
}
據我了解, ViewModelComponent
僅將SavedStateHandle
作為默認綁定,甚至 ViewModel 本身也沒有。
如果您的 UseCase 依賴於因此依賴於 UseCase 的 ViewModel 的范圍,則您有一個依賴循環並且您無法使用 Hilt 解決它。
您最好傳遞 UseCase 的提供者,並在 ViewModel 中對其進行初始化,或者更好的是,不依賴於 CoroutineScope 而是讓您的 UseCase 接口suspend
您可以將 KTX 擴展用於生命周期感知組件,並使用viewModelScope
擴展。 見這里。
我建議不要像@MrMikimn 提到的那樣從您的 viewModel 傳遞 scope 。 您可以在您的用例中使用新流程 API 執行以下操作:
suspend fun execute() = flow {
// some code
emit(SomeResult)
}
在你的 viewModel 里面是這樣的:
fun doSomething() = viewModelScope.launch {
myUseCaseInstance
.execute()
.flowOn(Dispatchers.IO)
.collect { result ->
// do something with result
}
}
這樣,執行 function 將在 viewModelScope 內運行,因此如果您的 ViewModel 被清除,它也會被取消。 如果您想對此進行更多控制,您還可以在 viewModel 中實例化一個 Job 並將 doSomething() function 分配給它,例如 val job: Job = doSomething() ,然后您可以進一步決定何時取消或重新觸發它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.