1 /*
2  * Copyright (C) 2023 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.healthconnect.controller.migration
17 
18 import androidx.lifecycle.LiveData
19 import androidx.lifecycle.MutableLiveData
20 import androidx.lifecycle.ViewModel
21 import androidx.lifecycle.viewModelScope
22 import com.android.healthconnect.controller.migration.api.LoadMigrationRestoreStateUseCase
23 import com.android.healthconnect.controller.migration.api.MigrationRestoreState
24 import dagger.hilt.android.lifecycle.HiltViewModel
25 import javax.inject.Inject
26 import kotlinx.coroutines.launch
27 import kotlinx.coroutines.runBlocking
28 
29 @HiltViewModel
30 class MigrationViewModel
31 @Inject
32 constructor(
33     private val loadMigrationRestoreStateUseCase: LoadMigrationRestoreStateUseCase,
34 ) : ViewModel() {
35 
36     private val _migrationState = MutableLiveData<MigrationFragmentState>()
37     val migrationState: LiveData<MigrationFragmentState>
38         get() = _migrationState
39 
40     init {
41         loadHealthConnectMigrationUiState()
42     }
43 
loadHealthConnectMigrationUiStatenull44     private fun loadHealthConnectMigrationUiState() {
45         viewModelScope.launch {
46             _migrationState.postValue(
47                 MigrationFragmentState.WithData(loadMigrationRestoreStateUseCase.invoke()))
48         }
49     }
50 
getCurrentMigrationUiStatenull51     fun getCurrentMigrationUiState(): MigrationRestoreState {
52         return runBlocking { loadMigrationRestoreStateUseCase.invoke() }
53     }
54 
55     sealed class MigrationFragmentState {
56         object Loading : MigrationFragmentState()
57 
58         object Error : MigrationFragmentState()
59 
60         data class WithData(val migrationRestoreState: MigrationRestoreState) :
61             MigrationFragmentState()
62     }
63 }
64