privatefunloadUsers() { // Do an asynchronous operation to fetch users. } }
然后,您可以从 Activity 访问该列表,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classMyActivity : AppCompatActivity() {
overridefunonCreate(savedInstanceState: Bundle?) { // Create a ViewModel the first time the system calls an activity's onCreate() method. // Re-created activities receive the same MyViewModel instance created by the first activity.
// Use the 'by viewModels()' Kotlin property delegate // from the activity-ktx artifact val model: MyViewModel by viewModels() //等同于 val model = ViewModelProvider(this).get(MyViewModel::class.java) model.getUsers().observe(this, Observer<List<User>>{ users -> // update UI }) } }
@Override public ViewModelStore getViewModelStore(){ if (getApplication() == null) { thrownew IllegalStateException("Your activity is not yet attached to the " + "Application instance. You can't request ViewModel before onCreate call."); } if (mViewModelStore == null) { NonConfigurationInstances nc = (NonConfigurationInstances) getLastNonConfigurationInstance(); if (nc != null) { // Restore the ViewModelStore from NonConfigurationInstances mViewModelStore = nc.viewModelStore; } if (mViewModelStore == null) { mViewModelStore = new ViewModelStore(); } } return mViewModelStore; }
factory
1 2 3 4 5 6 7 8 9 10 11 12
publicinterfaceFactory{ /** * Creates a new instance of the given {@code Class}. * <p> * * @param modelClass a {@code Class} whose instance is requested * @param <T> The type parameter for the ViewModel. * @return a newly created ViewModel */ @NonNull <T extends ViewModel> T create(@NonNull Class<T> modelClass); }
@Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass){ // ViewModelProvider calls correct create that support same modelClass with different keys // If a developer manually calls this method, there is no "key" in picture, so factory // simply uses classname internally as as key. String canonicalName = modelClass.getCanonicalName(); if (canonicalName == null) { thrownew IllegalArgumentException("Local and anonymous classes can not be ViewModels"); } return create(canonicalName, modelClass); }
/** * Clears internal storage and notifies ViewModels that they are no longer used. */ publicfinalvoidclear(){ for (ViewModel vm : mMap.values()) { vm.clear(); } mMap.clear(); } }
ViewModelStore viewModelStore = mViewModelStore; if (viewModelStore == null) { // No one called getViewModelStore(), so see if there was an existing // ViewModelStore from our last NonConfigurationInstance NonConfigurationInstances nc = (NonConfigurationInstances) getLastNonConfigurationInstance(); if (nc != null) { viewModelStore = nc.viewModelStore; } }
voidattachController(@NonNull FragmentHostCallback<?> host, @NonNull FragmentContainer container, @Nullablefinal Fragment parent){ if (mHost != null) thrownew IllegalStateException("Already attached"); mHost = host; mContainer = container; mParent = parent; if (mParent != null) { // Since the callback depends on us being the primary navigation fragment, // update our callback now that we have a parent so that we have the correct // state by default updateOnBackPressedCallbackEnabled(); } // Set up the OnBackPressedCallback if (host instanceof OnBackPressedDispatcherOwner) { OnBackPressedDispatcherOwner dispatcherOwner = ((OnBackPressedDispatcherOwner) host); mOnBackPressedDispatcher = dispatcherOwner.getOnBackPressedDispatcher(); LifecycleOwner owner = parent != null ? parent : dispatcherOwner; mOnBackPressedDispatcher.addCallback(owner, mOnBackPressedCallback); }
// Get the FragmentManagerViewModel if (parent != null) { mNonConfig = parent.mFragmentManager.getChildNonConfig(parent); } elseif (host instanceof ViewModelStoreOwner) { //这里,已经被初始化了 ViewModelStore viewModelStore = ((ViewModelStoreOwner) host).getViewModelStore(); mNonConfig = FragmentManagerViewModel.getInstance(viewModelStore); } else { mNonConfig = new FragmentManagerViewModel(false); } }