我正在使用 科因 作为 依赖注入(inject)模式 在我的项目中,每当我加载 fragment/Activity 时,我都需要创建新实例,现在使用以下模式,任何解决方案都可以节省大量时间。
private val homeViewModel: HomeViewModel by viewModel()
最佳答案
Define ViewModel as an abstract in BaseFragment class and set value when you extend your BaseFragment.
abstract class BaseFragment<Binding : ViewDataBinding, ViewModel : BaseViewModel> : Fragment(){
protected var bindingObject: Binding? = null
protected abstract val mViewModel: ViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
bindingObject = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false)
return bindingObject?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
performDataBinding()
}
@LayoutRes
abstract fun getLayoutResId(): Int
private fun performDataBinding() {
bindingObject?.setLifecycleOwner(this)
bindingObject?.setVariable(BR.viewModel, mViewModel)
bindingObject?.executePendingBindings()
}
}
And in your fragment
class FragmentNew : BaseFragment<FragmentNewBinding, FragmentNewVM>() {
// Here is the your viewmodel imlementation. Thus when you create fragment it's by default override method
override val mViewModel: FragmentNewVM by viewModel()
override fun getLayoutResId(): Int = [fragment layout id like "R.layout.fragment_new"]
}
关于android - 每次如何在koin中创建viewModel的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56625152/