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