1 /** 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * ``` 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * ``` 10 * 11 * Unless required by applicable law or agreed to in writing, software distributed under the License 12 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 * or implied. See the License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 package com.android.healthconnect.controller.categories 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.shared.usecase.UseCaseResults 23 import dagger.hilt.android.lifecycle.HiltViewModel 24 import javax.inject.Inject 25 import kotlinx.coroutines.launch 26 27 @HiltViewModel 28 class HealthDataCategoryViewModel 29 @Inject 30 constructor( 31 private val loadCategoriesUseCase: LoadHealthCategoriesUseCase, 32 ) : ViewModel() { 33 34 private val _categoriesData = MutableLiveData<CategoriesFragmentState>() 35 /** 36 * Provides a list of HealthDataCategories displayed in {@link HealthDataCategoriesFragment}. 37 */ 38 val categoriesData: LiveData<CategoriesFragmentState> 39 get() = _categoriesData 40 41 init { 42 loadCategories() 43 } 44 loadCategoriesnull45 fun loadCategories() { 46 _categoriesData.postValue(CategoriesFragmentState.Loading) 47 viewModelScope.launch { 48 when (val result = loadCategoriesUseCase()) { 49 is UseCaseResults.Success -> { 50 _categoriesData.postValue(CategoriesFragmentState.WithData(result.data)) 51 } 52 is UseCaseResults.Failed -> { 53 _categoriesData.postValue(CategoriesFragmentState.Error) 54 } 55 } 56 } 57 } 58 59 sealed class CategoriesFragmentState { 60 object Loading : CategoriesFragmentState() 61 object Error : CategoriesFragmentState() 62 data class WithData(val categories: List<HealthCategoryUiState>) : 63 CategoriesFragmentState() 64 } 65 } 66