RxSwift extensions for Swift optionals and "Occupiable" types.
All operators are also available on Driver
and Signal
, unless otherwise noted.
Observable<String?>
.of("One", nil, "Three")
.filterNil()
// Type is now Observable<String>
.subscribe { print($0) }
next(One)
next(Three)
completed
Observable<String?>
.of("One", nil, "Three")
.replaceNilWith("Two")
// Type is now Observable<String>
.subscribe { print($0) }
next(One)
next(Two)
next(Three)
completed
Unavailable on Driver
, because Driver
s cannot error out.
By default errors with RxOptionalError.foundNilWhileUnwrappingOptional
.
Observable<String?>
.of("One", nil, "Three")
.errorOnNil()
// Type is now Observable<String>
.subscribe { print($0) }
next(One)
error(Found nil while trying to unwrap type <Optional<String>>)
Observable<String?>
.of("One", nil, "Three")
.catchOnNil {
return Observable<String>.just("A String from a new Observable")
}
// Type is now Observable<String>
.subscribe { print($0) }
next(One)
next(A String from a new Observable)
next(Three)
completed
Observable<Int?>
.of(5, 6, 6, nil, nil, 3)
.distinctUntilChanged()
.subscribe { print($0) }
next(Optional(5))
next(Optional(6))
next(nil)
next(Optional(3))
completed
Occupiables are:
String
Array
Dictionary
Set
Currently in Swift protocols cannot be extended to conform to other protocols.
For now the types listed above conform to Occupiable
. You can also conform
custom types to Occupiable
.
Observable<[String]>
.of(["Single Element"], [], ["Two", "Elements"])
.filterEmpty()
.subscribe { print($0) }
next(["Single Element"])
next(["Two", "Elements"])
completed
Unavailable on Driver
, because Driver
s cannot error out.
By default errors with RxOptionalError.emptyOccupiable
.
Observable<[String]>
.of(["Single Element"], [], ["Two", "Elements"])
.errorOnEmpty()
.subscribe { print($0) }
next(["Single Element"])
error(Empty occupiable of type <Array<String>>)
Observable<[String]>
.of(["Single Element"], [], ["Two", "Elements"])
.catchOnEmpty {
return Observable<[String]>.just(["Not Empty"])
}
.subscribe { print($0) }
next(["Single Element"])
next(["Not Empty"])
next(["Two", "Elements"])
completed
- Run
pod install
in Example directory - Select RxOptional Examples target
- Build
- Show Debug Area (cmd+shift+Y)
- Click blue play button in Debug Area
RxOptional is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'RxOptional'
Add this to Cartfile
github "RxSwiftCommunity/RxOptional" ~> 4.1.0
$ carthage update
To use RxOptional as a Swift Package Manager package just add the following in your Package.swift file.
import PackageDescription
let package = Package(
name: "ProjectName",
dependencies: [
.Package(url: "https://github.com/RxSwiftCommunity/RxOptional")
]
)
Thane Gill, me@thanegill.com
RxOptional is available under the MIT license. See the LICENSE file for more info.