From 475ae827c478522a007053611d2e86674c69ee8f Mon Sep 17 00:00:00 2001 From: Parth Panchal Date: Wed, 5 Jun 2024 22:28:45 -0700 Subject: [PATCH] created LocationViewModel - added function to fetch locations from fhirEngine --- .../fhir/viewmodel/LocationViewModel.kt | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 app/src/main/java/org/openmrs/android/fhir/viewmodel/LocationViewModel.kt diff --git a/app/src/main/java/org/openmrs/android/fhir/viewmodel/LocationViewModel.kt b/app/src/main/java/org/openmrs/android/fhir/viewmodel/LocationViewModel.kt new file mode 100644 index 0000000..1c0f357 --- /dev/null +++ b/app/src/main/java/org/openmrs/android/fhir/viewmodel/LocationViewModel.kt @@ -0,0 +1,64 @@ +package org.openmrs.android.fhir.viewmodel + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import com.google.android.fhir.FhirEngine +import com.google.android.fhir.search.search +import kotlinx.coroutines.launch +import org.hl7.fhir.r4.model.Location + +class LocationViewModel(application: Application, private val fhirEngine: FhirEngine) : AndroidViewModel(application) { + + init { + getLocations() + } + + val locations = MutableLiveData>() + + private fun getLocations() { + viewModelScope.launch { + val locationsList : MutableList = mutableListOf() + fhirEngine.search { } + .mapIndexed { index, fhirLocation -> fhirLocation.resource.toLocationItem(index + 1) } + .let { locationsList.addAll(it) } + locations.value = locationsList + } + + } + + private fun Location.toLocationItem(position: Int): LocationItem { + return LocationItem( + id = position.toString(), + resourceId = idElement.idPart, + status = status.name, + name = name, + description = description + ) + } + + data class LocationItem( + val id:String, + val resourceId: String, + val status:String, + val name:String, + val description:String, + ) + + class LocationViewModelFactory( + private val application: Application, + private val fhirEngine: FhirEngine, + ) : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(LocationViewModel::class.java)) { + return LocationViewModel(application, fhirEngine) as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } + } + +} \ No newline at end of file