Swift & SwiftUI
  • İçerikler
  • UI Bileşenleri
    • Text
    • Button
    • Image
    • Picker
    • SecureField
    • Stepper
    • Slider
    • TabView
    • Sheet
    • Action Sheet
    • Alert
  • Layout
    • Fill-Space-Equally
  • State & Data Flow
    • Content
    • EnvironmentObject
    • ObservableObject
    • ObservedObject
    • Binding
  • Gestures
    • TapGesture
    • DragGesture
    • MagnificationGesture
    • RotationGesture
    • LongPressGesture
    • Notes
  • Extra
    • GeometryReader
    • Timer
    • AlignmentGuide
    • PreferenceKey
  • Concurrency
    • Perform asynchronous operation
Powered by GitBook
On this page

Was this helpful?

  1. State & Data Flow

ObservableObject

A type of object with a publisher that emits before the object has changed.

By default an ObservableObject will synthesize an objectWillChangepublisher that emits before any of its @Published properties changes

class DelayedUpdater: ObservableObject {
    
    @Published var value = 0
    // or, use below to add extra functionality.
    var value: Int {
        willSet {
            objectWillChange.send()
        }
    }
    
    init() {
        for i in 1...10 {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(i)) {
                self.value += 1
            }
        }
    }

}

struct ContentView: View {

    @ObservedObject var updater = DelayedUpdater()
    
    var body: some View {
        Text("value: \(updater.value)")
        // value: 0
        // value: 1
        // value: 2
        // ..
    } 
}
PreviousEnvironmentObjectNextObservedObject

Last updated 5 years ago

Was this helpful?