简体   繁体   English

RxSwift基于变量构建一个Observable

[英]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. 我正在尝试构建一个Observable,它将根据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! 不幸的是,map func中的bloc永远不会被调用!

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. fullName变量绑定到UITextField,并使用RxSwift示例中定义的双向运算符< - >。
  2. The isFullNameOKObs Observable will be observed to hide or display the submit button of my ViewController. 将观察到isFullNameOKObs Observable 隐藏或显示我的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: ViewController:

func bindModel() -> Void {

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

}

Do you need the two-way binding between the UITextField and your Variable ? 你需要UITextField和你的Variable之间的双向绑定吗?

If not, I would suggest you try to just use bindTo() instead like this: myTextField.rx.text.orEmpty.bindTo(fullName).disposed(by: disposeBag) 如果没有,我建议你尝试使用bindTo()如下所示: myTextField.rx.text.orEmpty.bindTo(fullName).disposed(by: disposeBag)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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