简体   繁体   中英

RxSwift subscribe to <Bool> change depend from one variable (MVVM)

Start learning RxSwift (Realm courses) and have some question.

In my controller have one TextField and Button, I need to subscribe for Button.isEnable when my TextField.count > 0

In courses this problem solved next code:

In Controller set value:

userNameText.rx.text.orEmpty.bind(to: viewModel.userName).disposed(by: disposeBag)
passwordText.rx.text.orEmpty.bind(to: viewModel.passwordValue).disposed(by: disposeBag)
viewModel.isValid.map{$0}.bind(to: button.rx.isEnabled).disposed(by: disposeBag)

In model:

let userName = Variable<String>("")
    let passwordValue = Variable<String>("")
    let isValid: Observable<Bool>

    init() {
        isValid = Observable.combineLatest(self.userName.asObservable(), self.passwordValue.asObservable()) {(name, password) in
            return  name.count > 0 && password.count > 0
        }
    }

In course use Observable.combineLatest for create observable with 2 value, for which we observe.(work with 2 value)

How create Observable where we work with one value??

PS Not work like this (min 2)

isValid = Observable.combineLatest(self.passwordValue.asObservable()) {(name) in
                return  name.count > 0 && password.count > 0
            }

Just do:

self.isValid = self.passwordValue.asObservable().map{ password in
    password.count > 0 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM