As ViewModelProviders.of() is deprecated, How should i create object of ViewModel?

前端 未结 10 1072
情深已故
情深已故 2020-12-14 14:05

I have been trying to create an Object of ViewModel in an Activity but ViewModelProviders is deprecated So what\'s the alternative to create the ViewModel\'s object.

相关标签:
10条回答
  • 2020-12-14 14:43

    ViewModelProviders.of() has been deprecated.

    Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.

    Java

     mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
    

    Kotlin

    mainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
    
    0 讨论(0)
  • 2020-12-14 14:43

    The simple option for the next several months is to stick with stable or beta versions. ViewModelProviders is only deprecated starting with 2.2.0, presently in an alpha03 release.

    For when you do move to 2.2.0 or higher of the lifecycle dependencies, your options depend on your language:

    • If you are using Java, use the ViewModelProvider() constructor, passing in your activity or fragment

    • If you are using Kotlin, there is supposed to be a by viewModels() property delegate, though I am not finding it in the source code...

    0 讨论(0)
  • 2020-12-14 14:44

    This code works for me

    private lateinit var viewModel: MainViewModel
    viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(MainViewModel::class.java)
    
    0 讨论(0)
  • 2020-12-14 14:45

    Simply replace:

    This:

    boardViewModel = ViewModelProviders.of(this).get(BoardViewModel::class.java)
    

    With this:

    boardViewModel = ViewModelProvider(this).get(BoardViewModel::class.java)
    
    0 讨论(0)
提交回复
热议问题