I have a swiftUi view depending on a class data. Before displaying the data, I have to compute it in .onAppear method.
I would like to make this heavy computation only when my observed object changes.
The problem is that .onAppear is called every time I open the view, but the object value does not change very often.
Is it possible to conditionally execute the compute function, only when observed data has effectively been modified ?
import SwiftUI
struct test2: View {
@StateObject var person = Person()
@State private var computedValue = 0
var body: some View {
List {
Text("age = \(person.age)")
Text("computedValue = \(computedValue)")
}
.onAppear {
computedValue = compute(person.age) /// Executed much too often :(
}
}
func compute(_ age: Int) -> Int {
return age * 2 /// In real life, heavy computing
}
}
class Person: ObservableObject {
var age: Int = 0
}
Thanks for advice :)
task(id:priority:_:) is the solution for that.
"A view that runs the specified action asynchronously when the view appears, or restarts the task with the id value changes."
Set the
id
param to the data you want to monitor for changes.