I have a list view of Task items. Every 10 seconds a timer triggers the function randomTasks that is responsible to modify the title and the description of each tasks in the list but the ListView doesn’t reflect the changes.I tried to use objectWillChange.send() but it doesn’t work.
I’ve noticed that when a task is modified with a different id the ListView updates and I can see the changes but when i’m in the detail view whenever randomTaskTitle is triggered the view is dismissed automatically.
class Task {
var id: String = UUID().uuidString
var title: String
var description: String
init(title: String, description: String) {
self.title = title
self.description = description
}
}
import SwiftUI
struct TasksView: View {
@EnvironmentObject var viewModel: TasksViewModel
let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView {
List {
ForEach(viewModel.tasks, id: \.id) { task in
NavigationLink(
destination: DetailView(task: task)
) {
VStack {
Text(task.title)
Text(task.description)
}
}
}
}
.onReceive(timer) { time in
Task {
await viewModel.randomTasks()
}
}
}
}
struct TasksViewNew_Previews: PreviewProvider {
static var previews: some View {
TasksView()
}
}
import Foundation
@MainActor
class TasksViewModel: ObservableObject {
@Published var tasks = [Task]()
init() {
self.tasks = [Task(title: "TaskA", description: "DescriptionA"),
Task(title: "TaskB", description: "DescriptionB"),
Task(title: "TaskC", description: "DescriptionC"),
Task(title: "TaskD", description: "DescriptionD"),]
}
func randomTasks() {
tasks.forEach { task in
task.title = randomTitleTask()
task.description = randomDescriptionTask()
}
}
}