1 /*
2  * Copyright 2024 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.lifecycle.viewmodel.CreationExtras
19 import kotlin.jvm.JvmOverloads
20 import kotlin.reflect.KClass
21 
22 /**
23  * An implementation of [Lazy] used by [androidx.fragment.app.viewModels] and
24  * [androidx.activity.viewModels].
25  *
26  * [storeProducer] is a lambda that will be called during initialization, [VM] will be created in
27  * the scope of returned [ViewModelStore].
28  *
29  * [factoryProducer] is a lambda that will be called during initialization, returned
30  * [ViewModelProvider.Factory] will be used for creation of [VM]
31  *
32  * [extrasProducer] is a lambda that will be called during initialization, returned
33  * [HasDefaultViewModelProviderFactory] will get [CreationExtras] used for creation of [VM]
34  */
35 public class ViewModelLazy<VM : ViewModel>
36 @JvmOverloads
37 constructor(
38     private val viewModelClass: KClass<VM>,
39     private val storeProducer: () -> ViewModelStore,
40     private val factoryProducer: () -> ViewModelProvider.Factory,
<lambda>null41     private val extrasProducer: () -> CreationExtras = { CreationExtras.Empty }
42 ) : Lazy<VM> {
43     private var cached: VM? = null
44 
45     override val value: VM
46         get() {
47             val viewModel = cached
48             return if (viewModel == null) {
49                 val store = storeProducer()
50                 val factory = factoryProducer()
51                 val extras = extrasProducer()
<lambda>null52                 ViewModelProvider.create(store, factory, extras).get(viewModelClass).also {
53                     cached = it
54                 }
55             } else {
56                 viewModel
57             }
58         }
59 
isInitializednull60     override fun isInitialized(): Boolean = cached != null
61 }
62