Skip to content

Instantly share code, notes, and snippets.

@ncreated
Created July 17, 2017 20:34
Show Gist options
  • Save ncreated/4b3edb7a80028e75114330a0507b8279 to your computer and use it in GitHub Desktop.
Save ncreated/4b3edb7a80028e75114330a0507b8279 to your computer and use it in GitHub Desktop.
Medium blogpost snippet
func autocomplete(text: Observable<String>) -> (result: Driver<AutocompleteResult>,
isBusy: Driver<Bool>) {
let provider = self.provider
let resultAndLoading: Driver<(result: AutocompleteResult?, loading: Bool)> = text
.flatMapLatest { query -> Observable<(result: AutocompleteResult?, loading: Bool)> in
provider
.autocomplete(text: query)
.map { (result: .predictions($0), loading: false) }
.catchError { .just((result: .error($0), loading: false)) }
.startWith((result: nil, loading: true))
}
.asDriver(onErrorJustReturn: (result: .predictions([]), loading: false))
let result = resultAndLoading
.flatMap { (result, _) -> Driver<AutocompleteResult> in
if let result = result {
return Driver.just(result)
} else {
return Driver.empty()
}
}
let isLoading = resultAndLoading
.flatMap { (_, loading) -> Driver<Bool> in
return Driver.just(loading)
}
return (result: result, isBusy: isLoading)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment