1 /*
2  * Copyright (C) 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 
17 package com.android.intentresolver.ui.viewmodel
18 
19 import android.util.Log
20 import androidx.lifecycle.SavedStateHandle
21 import androidx.lifecycle.ViewModel
22 import com.android.intentresolver.ui.model.ActivityModel
23 import com.android.intentresolver.ui.model.ActivityModel.Companion.ACTIVITY_MODEL_KEY
24 import com.android.intentresolver.ui.model.ResolverRequest
25 import com.android.intentresolver.validation.Invalid
26 import com.android.intentresolver.validation.Valid
27 import dagger.hilt.android.lifecycle.HiltViewModel
28 import javax.inject.Inject
29 import kotlinx.coroutines.flow.MutableStateFlow
30 import kotlinx.coroutines.flow.StateFlow
31 import kotlinx.coroutines.flow.asStateFlow
32 
33 private const val TAG = "ResolverViewModel"
34 
35 @HiltViewModel
36 class ResolverViewModel @Inject constructor(args: SavedStateHandle) : ViewModel() {
37 
38     /** Parcelable-only references provided from the creating Activity */
39     val activityModel: ActivityModel =
<lambda>null40         requireNotNull(args[ACTIVITY_MODEL_KEY]) {
41             "ActivityModel missing in SavedStateHandle! ($ACTIVITY_MODEL_KEY)"
42         }
43 
44     /**
45      * Provided only for the express purpose of early exit in the event of an invalid request.
46      *
47      * Note: [request] can only be safely accessed after checking if this value is [Valid].
48      */
49     internal val initialRequest = readResolverRequest(activityModel)
50 
51     private lateinit var _request: MutableStateFlow<ResolverRequest>
52 
53     /**
54      * A [StateFlow] of [ResolverRequest].
55      *
56      * Note: Only safe to access after checking if [initialRequest] is [Valid].
57      */
58     lateinit var request: StateFlow<ResolverRequest>
59         private set
60 
61     init {
62         when (initialRequest) {
63             is Valid -> {
64                 _request = MutableStateFlow(initialRequest.value)
65                 request = _request.asStateFlow()
66             }
67             is Invalid -> Log.w(TAG, "initialRequest is Invalid, initialization failed")
68         }
69     }
70 }
71