SwiftUI : Receive Published values with conditions

113 Views Asked by At

I have an ObservableObject GlobalOO with a @Published value. In any view, I can observe changes with

.onReceive(globalOO.$value) { newValue in
    ...
}

Now I only want to receive those changes according to a condition in the view

@State private var isActive = false

.onReceive(globalOO.$value.drop(while: { _ in isActive == false })) { newValue in
    ...
}

This view modifier works but seems "weird". Is there any possibility to create a view modifier that does exactly the same but is more "compact"? Thank you.

1

There are 1 best solutions below

1
On

Try this!

struct ContentView: View {
    @ObservedObject var globalOO = GlobalOO()
    @State private var isActive = false

    var body: some View {
        Text("Hello, World!")
            .onReceive(globalOO.$value.drop(while: { _ in !isActive })) { newValue in
                // Handle newValue
            }
    }
}