android - 每次如何在koin中创建viewModel的新实例

标签 android mvvm viewmodel koin

我正在使用 科因 作为 依赖注入(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/

相关文章:

android - EventBus 在同一 fragment 中发布和订阅

android - 应用程序在加载 soundPool 文件 482 次后崩溃

WPF MVVM 将控件绑定(bind)到在 View 模型中设置的变量

android - 如何将 ViewModelScope 等异步协程范围的值返回到您的 UI?

Android:带有冰淇淋的奇怪按钮布局

Android,需要在我的ListView中将每个单词的第一个字母大写

c# - 尽管我们不能在 xaml 中应用它们,但是否有任何理由使用通用 View 模型?

mvvm - 声明 ReactiveCommand 后如何更新 CanExecute 值

wpf - 可以从 MVVM 中的 View 订阅 ViewModel 的 .NET 事件吗?

c# - 我是否需要在 MVC5 的 ViewModel 中实例化我的 Model 类?