RxSwift Creating an Observable Based on a Variable

I am trying to create an Observable that outputs a value based on the value of a variable.

Something like that:

let fullName = Variable<String>("") let isFullNameOKObs: Observable<Bool> isFullNameOKObs = fullName .asObservable() .map { (val) -> Bool in // here business code to determine if the fullName is 'OK' let ok = val.characters.count >= 3 return ok } 

Unfortunately, the block in the func function is never called!

The reason for this is that:

  • The fullName variable is bound to a UITextField with the bidirectional operator ↔, as defined in the RxSwift example.
  • It is observed that isFullNameOKObs Observable will hide or display the submit button of my ViewController.

Any help would be greatly appreciated.

thanks

Model

 class Model { let fullName = Variable<String>("") let isFullNameOKObs: Observable<Bool> let disposeBag = DisposeBag() init(){ isFullNameOKObs = fullName .asObservable() .debug("isFullNameOKObs") .map { (val) -> Bool in let ok = val.characters.count >= 3 return ok } .debug("isFullNameOKObs") isRegFormOKObs = Observable.combineLatest( isFullNameOKObs, is...OK, ... ) { $0 && $1 && ... } isRegFormOKObs .debug("isRegFormOKObs") .asObservable() .subscribe { (event) in // update the OK button } // removing this disposedBy resolved the problem //.disposed(by: DisposeBag()) } } 

ViewController:

 func bindModel() -> Void { _ = txFullName.rx.textInput <-> model!.fullName ...... } 
+7
ios swift observable rx-swift
source share
1 answer

Do you need two-way binding between UITextField and your Variable ?

If not, I suggest you instead just use bindTo() : myTextField.rx.text.orEmpty.bindTo(fullName).disposed(by: disposeBag)

+4
source share

All Articles