// ViewController.swiftimportUIKitimportRxSwiftimportRxCocoaclassViewController:UIViewController{// UI部品@IBOutletweakvarsampleBtn:UIButton!@IBOutletweakvarsampleTextField:UITextField!@IBOutletweakvarsampleLabel:UILabel!// 自動unsubscribeのために必要letdisposeBag=DisposeBag()overridefuncviewDidLoad(){super.viewDidLoad()// ボタンタップアクションself.sampleBtn.rx_tap.subscribeNext{[unownedself]_inself.showAlert()}.addDisposableTo(disposeBag)// テキストフィールドの入力アクションself.sampleTextField.rx_text.map{"Your Text is \($0)"}.bindTo(self.sampleTextField.rx_text).addDisposableTo(disposeBag)}<省略>funcshowAlert(){letalert=UIAlertController(title:"Sample Alert",message:"Can you see a sample alert?",preferredStyle:.Alert)letok=UIAlertAction(title:"OK",style:.Default){(action)in// 特に何もしない}alert.addAction(ok)presentViewController(alert,animated:true,completion:nil)}}
importFoundationimportUIKitimportRxSwiftimportRxCocoaletminimalUsernameLength=5letminimalPasswordLength=5classSimpleValidationViewController:ViewController{@IBOutletweakvarusernameOutlet:UITextField!@IBOutletweakvarusernameValidOutlet:UILabel!@IBOutletweakvarpasswordOutlet:UITextField!@IBOutletweakvarpasswordValidOutlet:UILabel!@IBOutletweakvardoSomethingOutlet:UIButton!overridefuncviewDidLoad(){super.viewDidLoad()usernameValidOutlet.text="Username has to be at least \(minimalUsernameLength) characters"passwordValidOutlet.text="Password has to be at least \(minimalPasswordLength) characters"// 注目!!letusernameValid=usernameOutlet.rx_text.map{$0.characters.count>=minimalUsernameLength}.shareReplay(1)letpasswordValid=passwordOutlet.rx_text.map{$0.characters.count>=minimalPasswordLength}.shareReplay(1)leteverythingValid=Observable.combineLatest(usernameValid,passwordValid){$0&&$1}.shareReplay(1)usernameValid.bindTo(passwordOutlet.rx_enabled).addDisposableTo(disposeBag)usernameValid.bindTo(usernameValidOutlet.rx_hidden).addDisposableTo(disposeBag)passwordValid.bindTo(passwordValidOutlet.rx_hidden).addDisposableTo(disposeBag)everythingValid.bindTo(doSomethingOutlet.rx_enabled).addDisposableTo(disposeBag)doSomethingOutlet.rx_tap.subscribeNext{[weakself]inself?.showAlert()}.addDisposableTo(disposeBag)}funcshowAlert(){letalertView=UIAlertView(title:"RxExample",message:"This is wonderful",delegate:nil,cancelButtonTitle:"OK")alertView.show()}}