With the implementation below, my SwiftUI view is not refreshing when data is retrieved from an HTTP request and stored in a view model controller class. The SwiftUI view calls a shared class of which is the parent of the view model controller, and the view model controller stores the data being accessed from the SwiftUI view.
GlobalDataManager:
@MainActor
@Observable class GlobalDataManager {
static let shared = GlobalDataManager()
var medications: MedicationsViewModel
private init() {
let medicationsVM = MedicationsViewModel()
self.medications = medicationsVM
medicationsVM.globalDataManager = self
}
}MedicationsViewModel:
@MainActor
@Observable final class MedicationsViewModel {
weak var globalDataManager: GlobalDataManager?
var medicationInformation: [MedicationInformation]
var asNeededMedications: [AsNeededMedication]
var timesMedicationsTaken: [TimeMedicationsTaken]
init(globalDataManager: GlobalDataManager? = nil) {
self.medicationInformation = []
self.asNeededMedications = []
self.timesMedicationsTaken = []
self.globalDataManager = globalDataManager
}
func request<T: Encodable>(data: T, requestType: RequestType) async {
do {
let response = try await HTTPRequestService.shared.request(requestType: requestType, body: data, dataID: nil)
if response.success {
let decodedData = try DataDecoderService.shared.decode(MedicationData.self, from: response.data)
medicationInformation = decodedData.medicationInformation
asNeededMedications = decodedData.asNeededMedications
timesMedicationsTaken = decodedData.timesMedicationsTaken
}
} catch let error {
globalDataManager?.updateError(error.localizedDescription)
}
}
}Medications View:
struct Medications: View {
@State private var globalDataManager = GlobalDataManager.shared
@State var sheetOpen: Bool = false
var body: some View {
MedicationTimesList(medicationTimes: globalDataManager.medications.timesMedicationsTaken)
.sheet(isPresented: $sheetOpen) {
CreateAndUpdateMedicationInformation(viewModel: globalDataManager.medications, sheetOpen: $sheetOpen)
}
}}
Button within CreateAndUpdateMedicationInformation:
struct CreateAndUpdateMedicationInformation: View {
var viewModel: MedicationsViewModel
var body: some View {
WideButton(label: "Add Medication", buttonState: $buttonState)
.onChange(of: buttonState) { _, newState in
if newState {
let medicationInformation = MedicationInformation()
Task {
await viewModel.request(data: medicationInformation, requestType: .addNewMedication)
}
sheetOpen = false
}
}
}When pressing a button within the CreateAndUpdateMedicationInformation view, the request() function is called, which updates the variable timesMedicationTaken that is stores the data to be displayed in the Medications view. In the request function variables update, but the SwiftUI view does not. How can this be resolved so the Medications view refreshes when timesMedicationTaken and the other variables in the request() function are updated?
0
0
139