Skip to content

Instantly share code, notes, and snippets.

@d6u
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save d6u/565896f92803feb67cc2 to your computer and use it in GitHub Desktop.

Select an option

Save d6u/565896f92803feb67cc2 to your computer and use it in GitHub Desktop.
Custom RxSwift operators
func cachePrevious<E>(source: Observable<E>) -> Observable<(E?, E)> {
var previous: E?
return source >- map {
let pre = previous
previous = $0
return (pre, $0)
}
}
func flatMapEarliest<E, R>(transform: E -> Observable<R>) -> Observable<E> -> Observable<R> {
return { source in
var acceptNew = true
return source >- flatMap { (n: E) in
if !acceptNew {
return empty()
}
acceptNew = false
return create { o in
let subscription = transform(n)
>- subscribe { e in
return send(o, e)
}
return AnonymousDisposable {
subscription.dispose()
acceptNew = true
}
}
}
}
}
func flatMapLatest<E, R>(selector: E -> Observable<R>) -> Observable<E> -> Observable<R> {
return { $0 >- map(selector) >- switchLatest }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment