RxSwift: Two way binding

2019-04-02 00:37发布

I used official two-way-binding solution

func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable{
let bindToUIDisposable = variable.asObservable()
    .bindTo(property)

let bindToVariable = property
    .subscribe(onNext: { n in
        variable.value = n
    }, onCompleted:  {
        bindToUIDisposable.dispose()
    })

return Disposables.create(bindToUIDisposable, bindToVariable)
}

Usage: (textField.rx.text <-> object.property).addDisposableTo(disposeBag)

Property definition: var property = Variable<String?>(nil)

  1. In onNext method all ok and variable changed its value, but my object.property doesn't changed.
  2. Is there any way to set variable current value into ControlProperty inside of <-> method, bcs I need set initial value, before subscribe starts?

1条回答
爷、活的狠高调
2楼-- · 2019-04-02 01:06

My fault. I replaced object with another instance after binding

This code works well and control property receive initial value from variable

查看更多
登录 后发表回答