1

So I have been following the Android ViewModel Overview as I need to communicate between fragments, when creating the ViewModel, it uses ViewModelProviders which requires you to add dependencies. Upon looking at the documentation for ViewModelProviders I saw this: Deprecation message

Should I continue to follow the Overview, adding the required dependencies, or should I modify it to use ViewModelProvider? What are the benefits of either?

Thank you.

RyanJ
  • 158
  • 10

2 Answers2

2

You should avoid using deprecated APIs. Deprecation means that it's planned to be removed and it's not going to be maintained.

If you check the commit that added deprecation: https://android-review.googlesource.com/c/platform/frameworks/support/+/1009889/6

If you check the diff of the deprecated commit you can see that ViewModelProviders.of internally uses the suggested API. (see diff)

Release notes: https://developer.android.com/jetpack/androidx/releases/lifecycle#2.2.0-alpha03

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

So what that means is that you can achieve exactly the same thing using the constructor instead of the ViewModelProviders.of().

Giorgos Neokleous
  • 1,709
  • 1
  • 14
  • 25
  • That's what I've managed to do now, but I'm having issues with just using "ViewModelProvider(ViewModelStoreOwner)". My ViewModelProvider constructor only seems to be able to take 2 or 3 paramaters. ViewModelProvider(ViewModelStoreOwner owner, Factory factory) ViewModelProvider(ViewModelStore store, Factory factory) – RyanJ Nov 25 '19 at 20:14
  • Sorry, only 2 parameters. This is what I have had to use to get around it: model = new ViewModelProvider(this.getActivity(), new ViewModelProvider.NewInstanceFactory()).get(SharedViewModel.class); – RyanJ Nov 25 '19 at 20:21
  • 1
    If you're not seeing the single parameter constructor, then you're not on a new enough version of Lifecycle to be affected by the deprecation. You should either upgrade to the latest version (`2.2.0-rc02`) or just continue to use `ViewModelProviders.of()`, which is the correct thing to use on Lifecycle 2.1 – ianhanniballake Nov 25 '19 at 20:22
1

My take on this is to avoid using deprecated methods as much as possible. There is a good discussion about it here. As to benefits, I think the later might be better because is it part of a more recent iteration. I have tried both with an infinite vertical scrolling recyclerView, and I have not notice any big difference a part from the naming.

Maxime Claude
  • 965
  • 12
  • 27
  • It's just a shame that there isn't as much information out there on using ViewModelProvider. – RyanJ Nov 25 '19 at 19:10