4

In Android Components could I make application class as the owner of ViewModel so I use it across several activities? or there no walk around?

ViewModelProviders.of(application class not activity).get(MyViewModel.class);
amorenew
  • 10,760
  • 10
  • 47
  • 69
  • Please see this topic it might help https://stackoverflow.com/questions/44641121/share-viewmodel-between-fragments-that-are-in-different-activity – IgorOK Jun 12 '18 at 22:58
  • @IgorOK is there a good article about ViewModelProvider.Factory? – amorenew Jun 13 '18 at 00:01
  • 1
    amorenew not sure. I am looking for the same solution too and I haven't found solution better than discribed on link above. Unfortunately android documentation does not contain information how to share fragment states in different activities like, for example, Gmail application does on tablet ( – IgorOK Jun 13 '18 at 10:43

1 Answers1

1

An Application is not a LifecycleOwner, so you cannot use it as a scope for a ViewModel.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • what about this answer https://stackoverflow.com/questions/44641121/share-viewmodel-between-fragments-that-are-in-different-activity – amorenew Jun 13 '18 at 00:00
  • and is there a good article about ViewModelProvider.Factory – amorenew Jun 13 '18 at 00:01
  • 1
    @amorenew: Similarly, you could hack a custom subclass of `Application` to be a `LifecycleOwner`. But you are not gaining anything over just having a singleton. Instead, you are making your app more complex for no obvious benefit. – CommonsWare Jun 13 '18 at 00:03