SwiftUI pattern for handling independent events/triggers in self-contained Views?

I have a View which is self-contained, in that it handles its own state.

The View maintains a list of Particle models. The View manages the life cycle and rendering of each Particle.

I want to trigger the View to create a new Particle, in an ad-hoc fashion, say in response to a timer or user input.

Each Particle is independent. There can be any number of Particles managed by the View, thus any number of calls to the trigger.

Currently, I am using an @Observable view model.

The view model has a flag ‘particleRequested’.

To manage this flag, I call a convenience function on the view model:

func requestParticle() {
    guard particleRequested == false else { return }

    particleRequested = true
    
    // Wait a brief moment, then reset the flag.
    Task { @MainActor [weak self] in
        guard let self = self else { return }
        try await Task.sleep(for: .seconds(0.01))
        self.particleRequested = false
    }
}

In the View itself, I only observe changes to the flag:

.onChange(of: viewModel.particleRequested, { _, newValue in
    if newValue {
        addParticle()  // Modifies View's state.
    }
})

This feels… jank. The whole approach smells. Is there a better, cleaner way?

0

Your general idea is correct – use onChange to detect a change in a view update and perform the desired action. Your current code can be simplified a lot:

  • you don’t need a view model class
  • you don’t need to trigger the action on true. Trigger the action whenever the value changes
  • so there is no need to reset the value after a delay
struct Particles<Trigger: Equatable>: View {
    @State private var particles = [String]()
    let newParticleTrigger: Trigger
    
    var body: some View {
        List(particles, id: .self) {
            Text($0)
        }
        .onChange(of: newParticleTrigger) {
            particles.append(UUID().uuidString)
        }
    }
}

// Example usage:
struct ContentView: View {
    @State private var newParticleTrigger = false
    
    var body: some View {
        Button("Foo") {
            newParticleTrigger.toggle()
        }
        Particles(newParticleTrigger: newParticleTrigger)
    }
}

The same pattern is used in many SwiftUI built-in views and modifiers, such as PhaseAnimator, sensoryFeedback, task(id:) and arguably any presentation modifier like sheet, confirmationDialog etc.

If you have multiple different things you want to trigger, just put all the triggers into a struct,

struct Particles: View {
    struct Triggers: Hashable {
        fileprivate var trigger1 = false
        fileprivate var trigger2 = false
        fileprivate var trigger3 = false
        
        mutating func triggerThing1() {
            trigger1.toggle()
        }
        mutating func triggerThing2() {
            trigger2.toggle()
        }
        mutating func triggerThing3() {
            trigger3.toggle()
        }
    }
    
    let triggers: Triggers
    
    var body: some View {
        // ...

        .onChange(of: triggers.trigger1) {
            // ...
        }
        .onChange(of: triggers.trigger2) {
            // ...
        }
        .onChange(of: triggers.trigger3) {
            // ...
        }
    }
}

An alternative design is to use the environment:

extension EnvironmentValues {
    @Entry var trigger1: Bool = false
    @Entry var trigger2: Bool = false
    @Entry var trigger3: Bool = false
}

struct OnEnvironmentChange<Trigger: Equatable>: ViewModifier {
    let environmentValueKeyPath: WritableKeyPath<EnvironmentValues, Bool>
    let trigger: Trigger
    @State private var currentState = false
    
    func body(content: Content) -> some View {
        content
            .environment(environmentValueKeyPath, currentState)
            .onChange(of: trigger) {
                currentState.toggle()
            }
    }
}

extension View {
    func thing1<T: Equatable>(trigger: T) -> some View {
        modifier(OnEnvironmentChange(environmentValueKeyPath: .trigger1, trigger: trigger))
    }
    func thing2<T: Equatable>(trigger: T) -> some View {
        modifier(OnEnvironmentChange(environmentValueKeyPath: .trigger2, trigger: trigger))
    }
    func thing3<T: Equatable>(trigger: T) -> some View {
        modifier(OnEnvironmentChange(environmentValueKeyPath: .trigger3, trigger: trigger))
    }
}

struct Particles: View {
    @Environment(.trigger1) var trigger1
    @Environment(.trigger2) var trigger2
    @Environment(.trigger3) var trigger3
    var body: some View {
        // ...

        .onChange(of: trigger1) {
            // ...
        }
        .onChange(of: trigger2) {
            // ...
        }
        .onChange(of: trigger3) {
            // ...
        }
    }
}

This way, when using Particles, you don’t need to know about the triggers that you don’t want to trigger. Apply only the view modifiers that corresponds to the things you want to trigger.

// suppose this view only wants to trigger thing1
struct ContentView: View {
    @State private var thing1 = false
    
    var body: some View {
        Button("Foo") {
            thing1.toggle()
        }
        Particles()
            // then only apply this modifier
            .thing1(trigger: thing1)
            // don't need to care about thing2 or thing3
    }
}

6

This is your mistake: Currently, I am using an @Observable view model.

View structs are the view model and use state and binding for dynamic data. Put the state in the highest common parent View that needs it. Pass data down as a let for read only or binding for read/write (transform it if neccessary). Body is called when it changes in either case. This is called data flow. SwiftUI will diff the new body with the previous and use the diff to init/update/deinit the real UI objects, start/stop animations etc.

Seems to me though you might want to model the data that drives the particles separate from the view but it is hard to tell, depends if you want to load/save it.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật