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

拥有回忆 提交于 2020-02-01 22:13:19

问题


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.


回答1:


Simply replace:

This:

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

With this:

boardViewModel = ViewModelProvider(this).get(BoardViewModel::class.java)



回答2:


ViewModelProviders.of() has been deprecated. You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality. (aosp/1009889)

Please click here to see the solution




回答3:


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...




回答4:


If you're using Kotlin, instead of:

private lateinit var viewModel: EntityGridViewModel

[...]

// Deprecated
viewModel = ViewModelProviders.of(this).get(EntityGridViewModel::class.java)

You can use the nicer:

private val viewModel: EntityGridViewModel by viewModels()



回答5:


ViewModelProviders.of() has been deprecated.

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

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



回答6:


Declare your viewmodel :

private lateinit var mYourViewModel: YourViewModel

Intialize you viewmodel : (If in activity then pass this)

mYourViewModel= YourViewModel(this).get(YourViewModel::class.java)

Observer viewModel : (If in activity pass "this")

   mYourViewModel.yourMethodInViewModel().observe(this,
        Observer<Boolean> { isExhausted ->

            }
        })

Observer viewModel : (If in fragment pass "viewLifecycleOwner")

   mYourViewModel.yourMethodInViewModel().observe(viewLifecycleOwner,
        Observer<Boolean> { isExhausted ->
                // do stuff with this
            }
        })

Hope this will help.



来源:https://stackoverflow.com/questions/57534730/as-viewmodelproviders-of-is-deprecated-how-should-i-create-object-of-viewmode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!