Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Last active September 16, 2017 07:50
Show Gist options
  • Select an option

  • Save daltonclaybrook/cdadfd2172defe583c992d7df9f7aa40 to your computer and use it in GitHub Desktop.

Select an option

Save daltonclaybrook/cdadfd2172defe583c992d7df9f7aa40 to your computer and use it in GitHub Desktop.
When a UISwitch changes to "on," a network request is performed, then the switch is flipped back off again.
import Moya
import RxCocoa
import RxSwift
import UIKit
func bindSwitchToTeamFetch(_ aSwitch: UISwitch) {
let teamsRequest = observeAllTeams()
aSwitch
.rx
.isOn // an Observable mirror of UISwitch.isOn
.filter { $0 == true }
.do(onNext: { _ in
aSwitch.isEnabled = false
})
.flatMap { _ in
return teamsRequest
}
.do(onNext: { [weak self] teams in
self?.reload(with: teams)
aSwitch.isEnabled = true
})
.map { _ in return false }
.bind(to: aSwitch.rx.isOn)
.disposed(by: self.disposeBag)
}
func observeAllTeams() -> Observable<[Team]> {
return self.apiProvider
.request(.allTeams)
.asObservable()
.mapModel(model: Team.self, errorModel: APIError.self)
.toArray()
.catchError { [weak self] error in
self?.handleSwitchError(error)
return .just([])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment