1 /* <lambda>null2 * 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 */ 18 package com.android.healthconnect.controller.shared.app 19 20 import android.health.connect.GetMedicalDataSourcesRequest 21 import android.health.connect.HealthConnectManager 22 import android.health.connect.datatypes.MedicalDataSource 23 import android.util.Log 24 import androidx.core.os.asOutcomeReceiver 25 import com.android.healthconnect.controller.service.IoDispatcher 26 import java.util.concurrent.Executors 27 import javax.inject.Inject 28 import javax.inject.Singleton 29 import kotlinx.coroutines.CoroutineDispatcher 30 import kotlinx.coroutines.suspendCancellableCoroutine 31 import kotlinx.coroutines.withContext 32 33 /** Reads MedicalDataSource from the DB. */ 34 @Singleton 35 class MedicalDataSourceReader 36 @Inject 37 constructor( 38 private val healthConnectManager: HealthConnectManager, 39 @IoDispatcher private val dispatcher: CoroutineDispatcher, 40 ) { 41 companion object { 42 private const val TAG = "MedicalDataSourceReader" 43 } 44 45 suspend fun fromPackageName(packageName: String): List<MedicalDataSource> = 46 withContext(dispatcher) { 47 val request = GetMedicalDataSourcesRequest.Builder().addPackageName(packageName).build() 48 try { 49 val medicalDataSources = 50 suspendCancellableCoroutine<List<MedicalDataSource>> { continuation -> 51 healthConnectManager.getMedicalDataSources( 52 request, 53 Runnable::run, 54 continuation.asOutcomeReceiver(), 55 ) 56 } 57 medicalDataSources 58 } catch (e: Exception) { 59 Log.e(TAG, "Error reading MedicalDataSource from package name.", e) 60 emptyList() 61 } 62 } 63 64 suspend fun fromDataSourceId(dataSourceId: String): List<MedicalDataSource> = 65 withContext(dispatcher) { 66 try { 67 val medicalDataSources = 68 suspendCancellableCoroutine<List<MedicalDataSource>> { continuation -> 69 healthConnectManager.getMedicalDataSources( 70 listOf(dataSourceId), 71 Executors.newSingleThreadExecutor(), 72 continuation.asOutcomeReceiver(), 73 ) 74 } 75 medicalDataSources 76 } catch (e: Exception) { 77 Log.e(TAG, "Error reading MedicalDataSource from ID.", e) 78 emptyList() 79 } 80 } 81 } 82