ios – SwiftUI – Replace physique solely as soon as when @EnviromentObject and @State adjustments


I’ve created this instance undertaking replicating my app structure, during which a random quantity is generated in a Supervisor class after which displayed within the SecondaryView. Inside this view, calculations must be made primarily based on this randomNumber and displayed as properly (randomNumberTimesTen). This instance is after all non-sensical and may very well be mounted by altering the structure. The necessary half is the relation between @State and @EnvironmentObject and they should keep the place they’re.

How can I be sure that the physique of SecondaryView is barely up to date as soon as after the randomNumberTimesTen has been calculated and never twice? In the intervening time it occurs straight away after the randomNumber was generated and this causes points in my app as I want the worth of randomNumberTimesTen earlier than the physique may be drawn appropriately.

I believe the problematic half is perhaps the .onChange(of: supervisor.randomNumber) as that is most likely solely executed when the physique is up to date. Is there a method to transfer this some other place? The multiplyByTen() wants to remain within the SecondaryView although.

Instance code:

struct ContentView: View {
    @StateObject var supervisor = Supervisor()
    var physique: some View {
        VStack {
            SecondaryView()
                .environmentObject(supervisor)
            Button("Random Quantity") {
                supervisor.generateRandomNumber()
            }
        }
    }
}

struct SecondaryView: View {
    @State var randomNumberTimesTen: Int = 0
    @EnvironmentObject var supervisor: Supervisor

    var physique: some View {

        VStack {
            Textual content("Random Quantity: (supervisor.randomNumber)")
            Textual content("Random Quantity x10: (randomNumberTimesTen)")
        }
        .onChange(of: supervisor.randomNumber) { _ in
            multiplyByTen()
        }
    }

    func multiplyByTen() {
        randomNumberTimesTen = supervisor.randomNumber * 10
    }
}


public class Supervisor: ObservableObject {
    @Revealed public var randomNumber: Int = 0

    public func generateRandomNumber() {
        self.randomNumber = Int.random(in: 0..<10)
    }
}

See also  android - Flutter I cant replace my textual content when i verify double variable with getx

Leave a Reply