Prevent SwiftUI Subview from redrawing

Viewed 575

I am making an app that gives the user information about their speed and heading and more. For the compass/heading, I created a subview that is displayed under the speed on the main content view.

However, whenever the model/model view providing the CoreLocation information about the users speed updates, it causes the entire content view to refresh making the compass look like it is twitching.

Is there a way to make it so that changes to the observed object or state variable do not cause a subview to redraw? Below is a video of what is happening and a shortened version of my code.

struct ContentView: View {
    
    @ObservedObject var locationViewModel = LocationManager()
    @State private var showMoreInfo: Bool = false
    @State private var showingTopSpeed: Bool = false
    
    @State var showingSettingsScreen: Bool = false
    
    private var currentSpeed: String = "Your current speed is:"
    private var topSpeed: String = " Your top speed is:"
    
    var body: some View {
        VStack {
            SpeedView(speed: showingTopSpeed ? locationViewModel.userSpeed : locationViewModel.userTopSpeed)
            
            if showMoreInfo {
                Text(String(format: "With an accuracy of: +/- %.2f", locationViewModel.userSpeedAccuracy * 2.236936))
                    .animation(.easeInOut)
            }
            
            Spacer()
            
            HStack {
                CompassView()
                    .padding()
            }
            .padding()
        }
        .padding()
    }
}

Video With Issue

Here is the code from my CompassHeading class that determines the degrees of rotation on the compass. How can I prevent it form resetting to 0 each time it is redrawn?

 var objectWillChange = PassthroughSubject<Void, Never>()
    var degrees: Double = .zero {
        didSet {
            objectWillChange.send()
        }
    }
0 Answers
Related