1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.lifecycle; 18 19 import java.util.HashMap; 20 21 /** 22 * Class to store {@code ViewModels}. 23 * <p> 24 * An instance of {@code ViewModelStore} must be retained through configuration changes: 25 * if an owner of this {@code ViewModelStore} is destroyed and recreated due to configuration 26 * changes, new instance of an owner should still have the same old instance of 27 * {@code ViewModelStore}. 28 * <p> 29 * If an owner of this {@code ViewModelStore} is destroyed and is not going to be recreated, 30 * then it should call {@link #clear()} on this {@code ViewModelStore}, so {@code ViewModels} would 31 * be notified that they are no longer used. 32 * <p> 33 * Use {@link ViewModelStoreOwner#getViewModelStore()} to retrieve a {@code ViewModelStore} for 34 * activities and fragments. 35 */ 36 public class ViewModelStore { 37 38 private final HashMap<String, ViewModel> mMap = new HashMap<>(); 39 put(String key, ViewModel viewModel)40 final void put(String key, ViewModel viewModel) { 41 ViewModel oldViewModel = mMap.put(key, viewModel); 42 if (oldViewModel != null) { 43 oldViewModel.onCleared(); 44 } 45 } 46 get(String key)47 final ViewModel get(String key) { 48 return mMap.get(key); 49 } 50 51 /** 52 * Clears internal storage and notifies ViewModels that they are no longer used. 53 */ clear()54 public final void clear() { 55 for (ViewModel vm : mMap.values()) { 56 vm.onCleared(); 57 } 58 mMap.clear(); 59 } 60 } 61