Chapter 6: Using Timeline View, onChange generally

When setting up TimerView and CountdownView you have CountdownTimer own updating timeRemaining with

    var body: some View {
        Text("\(timeRemaining)")  // 5
            .font(.system(size: size, design: .rounded))
            .padding()
            .onChange(of: date) { oldValue, newValue in
                timeRemaining -= 1
            }
    }

Delegating that responsibility to the body of some subview via binding seems messy, you should just do that w/in the context block of TimelineView.animation

        TimelineView(
            .animation(
                minimumInterval: 1.0,
                paused: timeRemaining <= 0)) { context in
                    CountdownView(  // 4
                        date: context.date,
                        timeRemaining: $timeRemaining,
                        size: size)
                    .onChange(of: context.date) { oldValue, newValue in
                        timeRemaining -= 1
                    }
                }

As a general suggestion I’m finding the use of onChange, onAppear, etc functionally to be haphazardly implemented, often just attached to whatever view was most recently being discussed w/no regard to performance, data flow, or architecture. I realize to some extent this book is over indexing on using SwiftUI when in many instances you should probably setup your own modes/services outside of the SwiftUI view structs but still, I’m looking to this book to provide optimal patterns for SwiftUI development. For example in Chapter 7, attaching an onAppear() to a Image view w/in a foreach loop is a bad idea.

1 Like

Hello @shizam welcome to our community and i see this is your first time posting here. Thank you for taking out time to share your insight and suggestion on using a timeline view.

I have pinged the author of this chapter so he can also share his input on this points you highlighted. Thanks

hi Sam! this book is an intro to SwiftUI and iOS app development for people who know some programming language like Python or JavaScript. It isn’t meant to be the final word on the most efficient architecture, although we tried not to do anything horribly inefficient. In this case, we felt that decrementing timeRemaining belonged in the view that displayed this value.

I don’t know of any architectural analysis of where to use onChange etc. You could check out our other SwiftUI book, which is aimed at experienced iOS developers. Chapter 10 discusses onChange.

I’ll let @Caroline respond to your comment on Chapter 7.

3 Likes

I see, I had come to this book as an intro w/optimal architecture in mind but looking at the other book I see now how the two are positioned and that this book errs on the side of simplicity instead of getting into the weeds. I want the weeds so I’ll purchase the other book too thank you :slight_smile:

Sam

1 Like