I implemented async/ await and Result. An error thrown in my data adapter (DA) is routed properly into my domain store (DoS) and handled there in the Result .failure case as shown below.
But I struggle to display the error as an alert. Getting the following message.
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
My domain store looks like this:
@MainActor
class TaskDoS: ObservableObject{
@Published var tasks: [TaskModel] = []
@Published var errorMessage: String = ""
@Published var showingError = false
var dataDS: TaskDS
init(dataDS: ITaskDataService) {
self.dataDS = TaskDS(dataDA: dataDS)
}
//loader for tasks.
func loadTasks() async {
let result = await dataDS.readTasks()
switch result {
case .success(let tasks):
self.tasks = tasks
case .failure(let error):
//I tried to run this code inside a DispatchQueue.main.async closure but without effects.
self.errorMessage = error.guidance
self.showingError.toggle()
DebugPrint.value(error, prompt: "TaskDoS:loadTask:")
}
}
}
The corresponding screen looks like this:
struct TaskListScreen: View {
@EnvironmentObject private var taskDoS: TaskDoS
@State private var editTask: String = "" //mock type.
var selectedCatalogue: String = "mockTaskCopy" //mockTaskPaste.
var body: some View {
NavigationStack {
List {
ForEach(taskDoS.tasks) { task in
Text(selectedCatalogue == "mockTaskCopy" ? "copy task(task)" : "paste task(task)")
}
}
.task {
await taskDoS.loadTasks()
}
//this alert can't be shown.
.alert("Error", isPresented: $taskDoS.showingError) {
} message: {
Text(taskDoS.errorMessage)
}
}
}
}
New contributor
MatFetsch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.