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 com.android.photopicker.core
17 
18 import androidx.compose.runtime.Composable
19 import androidx.compose.runtime.CompositionLocalProvider
20 import androidx.compose.runtime.getValue
21 import androidx.compose.ui.platform.LocalSavedStateRegistryOwner
22 import androidx.hilt.navigation.compose.hiltViewModel
23 import androidx.lifecycle.ViewModel
24 import androidx.lifecycle.compose.LocalLifecycleOwner
25 import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
26 import androidx.lifecycle.viewmodel.compose.viewModel
27 import com.android.photopicker.core.configuration.LocalPhotopickerConfiguration
28 import com.android.photopicker.core.configuration.PhotopickerRuntimeEnv
29 import com.android.photopicker.core.embedded.LocalEmbeddedLifecycle
30 
31 /**
32  * A composable function that obtains the requested [ViewModel] based on the current
33  * [PhotopickerRuntimeEnv]. This will re-use existing view models in the current [ViewModelStore]'s
34  * context, or create a new view model if the correct type cannot be found.
35  *
36  * This should be used in place of all other view model constructors, both [hiltViewModel] and
37  * [viewModel] as well as directly calling a ViewModel's public constructor. This ensures the
38  * created view model is properly re-used, and it is cleared when the ViewModelStore is cleared.
39  *
40  * @param <VM> the type of the viewModel to obtain
41  * @return the current instance of the view model, or a newly created view model if none existed in
42  *   the [ViewModelStore]
43  */
44 @Composable
obtainViewModelnull45 inline fun <reified VM : ViewModel> obtainViewModel(): VM {
46     val configuration = LocalPhotopickerConfiguration.current
47     var viewModel: VM =
48         when (configuration.runtimeEnv) {
49             // When the current runtime is embedded, override the current ViewModelStore to use
50             // the [LocalEmbeddedLifecycle]'s store, and rely on the [EmbeddedViewModelFactory]
51             // to create and inject view models.
52             PhotopickerRuntimeEnv.EMBEDDED -> {
53                 val embeddedLifecycle = LocalEmbeddedLifecycle.current
54                 checkNotNull(embeddedLifecycle) {
55                     "Cannot obtain view models in embedded runtime when" +
56                         " LocalEmbeddedLifecycle is not set."
57                 }
58                 var embeddedViewModel: VM? = null
59                 CompositionLocalProvider(
60                     LocalViewModelStoreOwner provides embeddedLifecycle,
61                     LocalLifecycleOwner provides embeddedLifecycle,
62                     LocalSavedStateRegistryOwner provides embeddedLifecycle,
63                 ) {
64                     embeddedViewModel =
65                         viewModel(
66                             embeddedLifecycle,
67                             factory = embeddedLifecycle.defaultViewModelProviderFactory
68                         )
69                 }
70                 // This should never actually be null, as the [EmbeddedViewModelFactory] will throw
71                 // an error rather than return a null value, but we need to de-null the type before
72                 // returning it to the calling composable.
73                 checkNotNull(embeddedViewModel) {
74                     "Unable to obtain viewmodel from embedded factory: ${VM::class.simpleName}"
75                 }
76             }
77             // When the current run time is activity, rely on the standard hiltViewModel injection,
78             // which scopes the view model to the navigation graph's current backstack entry.
79             PhotopickerRuntimeEnv.ACTIVITY -> hiltViewModel()
80         }
81     return viewModel
82 }
83