Skip to content

Instantly share code, notes, and snippets.

@chakrit
Created July 26, 2016 08:22
Show Gist options
  • Save chakrit/ad8a8a59c3384a2f5bedc0b730df9c5d to your computer and use it in GitHub Desktop.
Save chakrit/ad8a8a59c3384a2f5bedc0b730df9c5d to your computer and use it in GitHub Desktop.
import Foundation
import RxSwift
// HACK: Since the built-in Optional<T> is a generic type, not a protocol we cannot apply
// constraints on it. This protocol allows us to constraint our Rx operators onto
// optional types
protocol OptionalType {
associatedtype WrappedType
}
extension Optional: OptionalType {
typealias WrappedType = Wrapped
}
extension ObservableType where E: OptionalType {
func filterNonNil() -> Observable<E.WrappedType> {
return self.filter({ $0 != nil })
.map({ $0 as! E.WrappedType })
}
}
let disposables = DisposeBag()
func test() {
Observable<String?>.of("hello", nil, "world", nil, "end")
.filterNonNil()
.subscribeNext({ print($0) })
.addDisposableTo(disposables)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment