in Education by
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 :) JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
It would probably be a little less code in the view model, but to do all of the calculations in the view, you will need a few changes. First, your class Person has no @Published variables, so it will never call for a state change. I have fixed that. Second, now that your state will update, you can add an .onReceive() to the view to keep track of when age updates. Third, and extremely important, to keep from blocking the main thread with the "heavy computing", you should implement Async Await. As a result, even though I sleep the thread for 3 seconds, the UI is still fluid. struct test2: View { @StateObject var person = Person() @State private var computedValue = 0 var body: some View { List { Text("age = \(person.age)") Text("computedValue = \(computedValue)") Button { person.age = Int.random(in: 1...80) } label: { Text("Randomly Change Age") } } // This will do your initial setup .onAppear { Task { computedValue = await compute(person.age) /// Executed much too often :( } } // This will keep it current .onReceive(person.objectWillChange) { _ in Task { computedValue = await compute(person.age) /// Executed much too often :( } } } func compute(_ age: Int) async -> Int { //This is just to simulate heavy work. do { try await Task.sleep(nanoseconds: UInt64(3.0 * Double(NSEC_PER_SEC))) } catch { //handle error } return age * 2 /// In real life, heavy computing } } class Person: ObservableObject { @Published var age: Int = 0 }

Related questions

0 votes
    Can we execute any code before main method in Java?...
asked May 18, 2021 in Technology by JackTerrance
0 votes
    I have a batch file as follows; CD C:\MyFolder findstr /c:"stringToCheck" fileToCheck.bat IF NOT ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 13, 2022 in Education by JackTerrance
0 votes
    Buffer-overflow attack can take place if a machine can execute a code that resides in the data/stack segment. (a ... Security questions and answers pdf, mcq on Cyber Security pdf,...
asked Nov 4, 2021 in Education by JackTerrance
0 votes
    Can you execute javascript code from java 8 code base in Java8?...
asked Nov 8, 2020 in Education by Editorial Staff
0 votes
    I would like to specify an additional default shortcut class to a set of classes, similarly to that @each ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Jul 20, 2022 in Education by JackTerrance
0 votes
    So, I am creating an application which displays song lyrics for entered songs, however, longer songs do not ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 21, 2022 in Education by JackTerrance
0 votes
    Which of the following is method of System class is used to find how long a program takes to execute ... questions and answers pdf, java interview questions for beginners...
asked Oct 25, 2021 in Education by JackTerrance
0 votes
    Can we execute a program without main() method?...
asked Nov 19, 2020 in Education by Editorial Staff
0 votes
    ________ can be used to establish risk and stability estimations on an item of code, such as a class or method ... code (2)Defect density (3)Risk density (4)Cyclomatic complextiy...
asked May 15, 2021 in General by JackTerrance
0 votes
    _________ is an attack which forces an end user to execute unwanted actions on a web application in which ... , Database Interview Questions and Answers for Freshers and Experience...
asked Oct 11, 2021 in Education by JackTerrance
0 votes
    Suppose you have designed a Big Data batch using the MapReduce framework. Now you want to execute it on a cluster ... Run view? Name Node Data Node Resource Manager Job Tracker...
asked Mar 23, 2021 in Technology by JackTerrance
0 votes
    _____________ is a code injecting method used for attacking the database of a system / website. (a) HTML injection ... questions and answers pdf, mcq on Cyber Security pdf,...
asked Nov 5, 2021 in Education by JackTerrance
0 votes
    Which of the following methods is a method of wrapper Integer for obtaining hash code for the invoking object ... questions and answers pdf, java interview questions for beginners...
asked Oct 25, 2021 in Education by JackTerrance
0 votes
    Inviting a friend to help look for a hard to find vulnerability is a method of security code review. (1)True (2)False...
asked May 15, 2021 in General by JackTerrance
...