1 /*
<lambda>null2  * Copyright (C) 2020 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 com.android.permissioncontroller.permission.data
18 
19 import androidx.lifecycle.SavedStateHandle
20 
21 /**
22  * LiveData that loads wrapped value once. Once the wrapped data becomes non-stale it holds onto the
23  * value forever.
24  *
25  * This even extends over live-cycle events as the data is stored in the {@link SaveStateHandle}.
26  * This means that the data has to be writable to {@link SavedStateHandle} though, i.e. Serialzable,
27  * Parcelable, list, set, map, or a literal
28  */
29 class LoadAndFreezeLifeData<T>(
30     private val state: SavedStateHandle,
31     private val key: String,
32     private val wrapped: SmartUpdateMediatorLiveData<T>
33 ) : SmartUpdateMediatorLiveData<T>() {
34     init {
35         if (state.get<T>(key) == null) {
36             addSource(wrapped) { v ->
37                 if (wrapped.isInitialized) {
38                     value = v
39 
40                     if (!wrapped.isStale) {
41                         state.set(key, v)
42 
43                         removeSource(wrapped)
44                     }
45                 }
46             }
47         } else {
48             value = state[key]
49         }
50     }
51 
52     override fun onUpdate() {
53         // do nothing
54     }
55 }
56