Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift Build an Observable based on a Variable

I am trying to build an Observable which would output 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 bloc in the map func is never called!

The reason behind this is that:

  1. The fullName Variable is binded to a UITextField with the bidirectional operator <-> as defined in the RxSwift example.
  2. The isFullNameOKObs Observable will be observed to hide or display the submit button of my ViewController.

Any help would be greatly appreciated.

Thanks

The 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())

    }
}

The ViewController:

func bindModel() -> Void {

    _ = txFullName.rx.textInput <-> model!.fullName
    ......

}
like image 978
t4ncr3d3 Avatar asked Mar 07 '17 19:03

t4ncr3d3


1 Answers

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

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

like image 192
BStien Avatar answered Sep 28 '22 18:09

BStien