Last active
September 16, 2017 07:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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