Observe changes for key in Firebase database (async/await)

Swift, Async/await, Firebase

Observe changes for key in Firebase database using Swift's async/await

swift

import FirebaseDatabase import FirebaseDatabaseSwift public extension DatabaseQuery { func observe(_ eventType: DataEventType) -> AsyncThrowingStream<DataSnapshot, Error> { AsyncThrowingStream { continuation in let handle = observe( eventType, with: { snapshot in continuation.yield(snapshot) }, withCancel: { error in continuation.finish(throwing: error) } ) continuation.onTermination = { [unowned self] _ in removeObserver(withHandle: handle) } } } }

How to use?

do { let ref = Database.database().reference().child("foo") // Observe child added for try await snapshot in ref.observe(.childAdded) { print("Child added: \(snapshot.value)") } // Observe child changed for try await snapshot in ref.observe(.childChanged) { print("Child changed: \(snapshot.value)") } // Observe child moved for try await snapshot in ref.observe(.childMoved) { print("Child moved: \(snapshot.value)") } // Observe child removed for try await snapshot in ref.observe(.childRemoved) { print("Child removed: \(snapshot.value)") } // Observe any changes for try await snapshot in ref.observe(.value) { print("Child removed: \(snapshot.value)") } } catch { print("Observing failed with error: \(error)") }