我怎样才能告诉匕首使用我自己的ViewModelFactory而不是默认值? [英] How can I tell dagger hilt that use my own ViewModelFactory instead of default?
问题描述
代码: GalleryViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.jimmytrivedi.kotlin.imagesearchapp.data.UnsplashRepository
import dagger.assisted.Assisted
import javax.inject.Inject
class GalleryViewModel @Inject constructor(
private val repository: UnsplashRepository,
@Assisted state: SavedStateHandle
) :
ViewModel() {
private val currentQuery = state.getLiveData(CURRENT_QUERY, DEFAULT_QUERY)
val photos = currentQuery.switchMap { queryString ->
repository.getSearchResults(queryString).cachedIn(viewModelScope)
}
fun searchPhotos(query: String) {
currentQuery.value = query
}
companion object {
private const val CURRENT_QUERY = "current_query"
private const val DEFAULT_QUERY = "cats"
}
}
GalleryViewModelFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class GalleryViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
注意:请确保它一直运行到昨天,并且一切都正确.我刚刚更新了一些依赖项,并且陷入了无法创建类的实例的情况下……ViewModel ,因此,我在堆栈溢出时进行了搜索,并得到了正确的答案,但是在AS中单击GalleryViewModel,然后显示此内置类的用法: GalleryViewModelFactory_Factory ,但我想使用自己的自定义类来解决错误.
Note: Please make sure that it was working till yesterday, and everything is correct only. I just updated some dependecies and I got stuck with Cannot create an instance of class ... ViewModel, So, I searched on stack overflow, and got this proper answer with, but in my AS, when I click on GalleryViewModel, then usage is showing for this in-built class: GalleryViewModelFactory_Factory, but I want to use my own custom class to resolve the errors.
参考:
-
推荐答案
当我正确记住这一点时,可以在实例化视图模型时通过自定义viewmodelfactory.例如:
When I remember this correctly, you can pass your custom viewmodelfactory when you instantiate your viewmodel. For Example:
val myViewModel: MyViewModel by viewmodels { myViewModelFactory }
这篇关于我怎样才能告诉匕首使用我自己的ViewModelFactory而不是默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!