gpt4 book ai didi

android - BaseClass 中的 Kotlin 泛型。试图通过 BaseFragment 中的泛型类型获取 ViewModel

转载 作者:行者123 更新时间:2023-12-03 10:41:18 24 4
gpt4 key购买 nike

嘿,我想创建通过泛型类型获取 viewModel 的 BaseFragment 类:

abstract class BaseFragment<B : ViewDataBinding, VM : ViewModel> : DaggerFragment() {

val viewModel by viewModels<VM> { viewModelFactory }
...
}

// Native function
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
但出现错误 Cannot use 'VM' as reified type parameter. Use a class instead.是否有可能实现我想要做的事情?也许用其他方法?

最佳答案

找到了工作方式,但它足够干净吗?

abstract class BaseModelFragment<VM : ViewModel>(viewModelClass: KClass<VM>) : DaggerFragment() {

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory

val viewModel by viewModel(viewModelClass) { viewModelFactory }

private fun Fragment.viewModel(
clazz: KClass<VM>,
ownerProducer: () -> ViewModelStoreOwner = { this },
factoryProducer: (() -> ViewModelProvider.Factory)? = null,
) = createViewModelLazy(clazz, { ownerProducer().viewModelStore }, factoryProducer)
}
和用法:
open class SomeFragment : BaseModelFragment<CustomerSupportViewModel>(CustomerSupportViewModel::class) {
...
}
它已经过测试并且可以正常工作。任何想法如何改进它? :)

关于android - BaseClass 中的 Kotlin 泛型。试图通过 BaseFragment 中的泛型类型获取 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65342251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com