Recipes for Combining Observables in RxSwift

Combine Latest

func example(username: Observable<String>, password: Observable<String>) {
let credentials: Observable<(String, String)> = Observable.combineLatest(username, password)
//...
}
func example(imageObservables: [Observable<UIImage>]) {
let images: Observable<[UIImage]> = Observable.combineLatest(imageObservables)
//...
}
func example(pageNumber: Observable<Int>, searchTerm: Observable<String>) {
let pageAndTerm: Observable<(Int, String)> = Observable.combineLatest(pageNumber.startWith(1), searchTerm)
//...
}
func example(pageNumber: Observable<Int>) {
let pageAndItems: Observable<(Int, [Item])> = pageNumber
.flatMapLatest { page in
Observable.combineLatest(Observable.just(page), getItems(forPage: page))
}
}
func example(pageNumber: Observable<Int>) {
let pageAndItems: Observable<(Int, [Item])> = pageNumber
.flatMapLatest { page in
getItems(forPage: page)
.map { (page, $0) }
}
}

Zip

func example(imageServerRequests requests: [Single<Data>]) {
let images: Observable<[Data]> = Observable.zip(requests)
//...
}
func example(imageURLs: [URL]) {
let values: Observable<URL> = Observable.zip(Observable.from(imageURLs), Observable.interval(3, scheduler: MainScheduler.instance), resultSelector: { $0 })
//...
}

Merge

func example(pullToRefresh: Observable<Void>, tapToRefresh: Observable<Void>) {
let refresh: Observable<Void> = Observable.merge(pullToRefresh, tapToRefresh)
// ...
}
func example(startOver: Observable<Void>, nextPage: Observable<Void>) {
enum Action {
case startOver
case nextPage
}
let action: Observable<Action> = Observable.merge(startOver.map { .startOver }, nextPage.map { .nextPage })
}

WithLatestFrom

let selectedFamilyMember = input.selectedIndex
.withLatestFrom(familyMembers) { $1[$0.row] }

Concat

let results = Observable.concat(networkRequests)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store