Skip to content

Instantly share code, notes, and snippets.

@hfossli
Last active January 4, 2018 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hfossli/30394ba3caa30e2d16bbb20cb3d61726 to your computer and use it in GitHub Desktop.
Save hfossli/30394ba3caa30e2d16bbb20cb3d61726 to your computer and use it in GitHub Desktop.
RxSwift + optional
// MIT License
//
// Copyright (c) 2016 Thane Gill <me@thanegill.com>
// Copyright (c) 2014-2017 Art.sy, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// https://github.com/RxSwiftCommunity/RxOptional/blob/447444e02ee6a657495753f57cdb2fdb329dea99/Source/Observable%2BOptional.swift
// Some code originally from here: https://github.com/artsy/eidolon/blob/24e36a69bbafb4ef6dbe4d98b575ceb4e1d8345f/Kiosk/Observable%2BOperators.swift#L42-L62
// Credit to Artsy and @ashfurrow
import RxSwift
protocol OptionalType {
associatedtype Wrapped
var value: Wrapped? { get }
}
extension Optional: OptionalType {
var value: Wrapped? {
return self
}
}
extension Observable where Element: OptionalType {
func filterNil() -> Observable<Element.Wrapped> {
return flatMap { (element) -> Observable<Element.Wrapped> in
if let value = element.value {
return .just(value)
} else {
return .empty()
}
}
}
}