RxOptional provides operators for Observable, Driver, and Signal to handle Swift optionals. These operators allow you to filter, replace, or handle errors when an optional value is nil.
// filterNil: Removes nil values and unwraps the type
Observable<String?>
.of("One", nil, "Three")
.filterNil()
.subscribe { print($0) } // Outputs: One, Three
// replaceNilWith: Replaces nil with a specific value
Observable<String?>
.of("One", nil, "Three")
.replaceNilWith("Two")
.subscribe { print($0) } // Outputs: One, Two, Three
// errorOnNil: Errors if a nil is encountered.
// Note: Unavailable on Driver.
Observable<String?>
.of("One", nil, "Three")
.errorOnNil()
.subscribe { print($0) } // Errors with RxOptionalError.foundNilWhileUnwrappingOptional
// catchOnNil: Provides a fallback Observable when nil is encountered
Observable<String?>
.of("One", nil, "Three")
.catchOnNil {
return Observable<String>.just("A String from a new Observable")
}
.subscribe { print($0) } // Outputs: One, A String from a new Observable, Three
// distinctUntilChanged: Standard operator that works with optionals
Observable<Int?>
.of(5, 6, 6, nil, nil, 3)
.distinctUntilChanged()
.subscribe { print($0) } // Outputs: Optional(5), Optional(6), nil, Optional(3)