Reputation: 1248
I use MVVM in my project. But when i create App Widget he does not support LifecycleOwner in updateAppWidget()
var model: CurrencyViewModel
model = ViewModelProvider(this).get(CurrencyViewModel::class.java)
Do I have a chance to access the model from App Widget?
Upvotes: 2
Views: 3600
Reputation: 7
Due to this question, you might observeForever
your variables in viewModel without accessing for lifecycleOwner
. I hope I got you question right.
Upvotes: 1
Reputation: 1619
That's not what the ViewModelProvider is meant for. When the widget is running the activity might be destroyed together with it's ViewModels. The AppWidgetProvider itself doesn't really have a lifecycle.
If you want to get data from the App into the App Widget you should save it in SharedPreferences or a database.
/**
* Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
* is alive. More detailed explanation is in {@link ViewModel}.
* <p>
* It uses the {@link FragmentActivity#getDefaultViewModelProviderFactory() default factory}
* to instantiate new ViewModels.
*
* @param activity an activity, in whose scope ViewModels should be retained
* @return a ViewModelProvider instance
* @deprecated Use the 'by viewModels()' Kotlin property delegate or
* {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
* passing in the activity.
*/
@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
return new ViewModelProvider(activity);
}
Upvotes: 5