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 package androidx.lifecycle
17 
18 import androidx.annotation.RestrictTo
19 
20 /**
21  * Class to store `ViewModel`s.
22  *
23  * Instances of `ViewModelStore` must be retained through configuration changes. If the owner of a
24  * `ViewModelStore`, typically a [`ViewModelStoreOwner`], is destroyed and recreated due to a
25  * configuration change, the new owner must have the old instance of the `ViewModelStore`.
26  *
27  * If the owner of a `ViewModelStore` is destroyed and is _not_ going to be recreated, it should
28  * call [`clear`] on this `ViewModelStore` so that The `ViewModel`s stored by it are notified that
29  * they are no longer needed.
30  *
31  * Use [`ViewModelStoreOwner.getViewModelStore`] to retrieve a `ViewModelStore` for activities and
32  * fragments.
33  */
34 public open class ViewModelStore {
35 
36     private val map = mutableMapOf<String, ViewModel>()
37 
38     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
putnull39     public fun put(key: String, viewModel: ViewModel) {
40         val oldViewModel = map.put(key, viewModel)
41         oldViewModel?.clear()
42     }
43 
44     /** Returns the `ViewModel` mapped to the given `key` or null if none exists. */
45     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
getnull46     public operator fun get(key: String): ViewModel? {
47         return map[key]
48     }
49 
50     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
keysnull51     public fun keys(): Set<String> {
52         return HashSet(map.keys)
53     }
54 
55     /** Clears internal storage and notifies `ViewModel`s that they are no longer used. */
clearnull56     public fun clear() {
57         for (vm in map.values) {
58             vm.clear()
59         }
60         map.clear()
61     }
62 }
63