Observable is the easiest way to observe values in Swift.
How to
Create an Observable and MutableObservable
Using MutableObservable
you can create and observe event.
Using Observable
you can observe event, in order to avoid side-effects on our internal API.
Create Observer with custom onDispose functionality
In some cases Observables require resources while they're active that must be cleaned up when they're disposed of. To handle such cases you can pass an optional block to the Observable initializer to be executed when the Observable is disposed of.
Model Properties as @MutableObservable
Now mark your binded/mapped properties as observable and export public observable
Add an observer
Add an observer and specify the DispatchQueue
Change the value
Stop observing new values
Memory management
For a single observer you can store the returned Disposable
to a variable
For multiple observers you can add the disposable to a Disposal
variable
And always weakify self
when referencing self
inside your observer
Installation
CocoaPods
Observable is available through CocoaPods. To install
it, simply add the following line to your Podfile:
Swift Package Manager
Observable is available through Swift Package Manager
.
Swift Package Manager (SwiftPM) is a tool for automating the distribution of Swift code.
It is integrated into the swift compiler and from Xcode 11, SwiftPM got natively integrated with Xcode.
Migrations
1.x.y to 2.0.0
Observable
is nowMutableObservable
ImmutableObservable
is nowObservable
Observable.asImmutableObservable()
is nowObservable.asObservable()
Observable.value
is nowObservable.wrappedValue
Suggestions or feedback?
Feel free to create a pull request, open an issue or find me on Twitter.