Skip to content

Instantly share code, notes, and snippets.

@levantAJ
Created May 27, 2021 04:14
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 levantAJ/c93b92566b27e6125f6e8e8607d6b650 to your computer and use it in GitHub Desktop.
Save levantAJ/c93b92566b27e6125f6e8e8607d6b650 to your computer and use it in GitHub Desktop.
Get previous & current value of a Observable
extension ObservableType {
func withPrevious() -> Observable<(previous: Element?, current: Element?)> {
return scan([]) { (previous, current) in
return Array(previous + [current]).suffix(2)
}
.map { array -> (previous: Element?, current: Element?) in
let previous = array.count > 1 ? array.first : nil
let current = array.last
return (previous, current)
}
}
func withPrevious(startWith first: Element) -> Observable<(Element, Element)> {
return scan((first, first)) { ($0.1, $1) }.skip(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment