pgb
pgb

Reputation: 25001

RxSwift initial value when binding a Variable

I have the following code:

import RxSwift
import RxCocoa

class ViewModel {

    var text = Variable<String>("")

    init() {
        text.value = "hello"
    }

}

class ViewController: UIViewController {
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var counterLabel: UILabel!

    var viewModel = ViewModel()

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.rx.text
            .orEmpty
            .debug()
            .bind(to: viewModel.text)
            .disposed(by: disposeBag)
    }
}

The binding works fine (when I change the UITextView it properly updates the viewModel. However, since the binding is unidirectional (or so I understand), the textView doesn't start with the value I set in the ViewModel's init method.

I can do textView.text = viewModel.text.value just before the binding, but since I'm using RxSwift, I want to understand what's the usual practice here.

Upvotes: 4

Views: 3990

Answers (1)

Cl&#233;ment Mangin
Cl&#233;ment Mangin

Reputation: 434

You are right, this is a unidirectional binding and you'd have to set the initial value of your text view manually. If you want bidirectional binding, take a look at the following code:

RxSwift: Two way binding

Be sure to import the Operators.swift file in your project (https://github.com/ReactiveX/RxSwift/blob/master/RxExample/RxExample/Operators.swift)

Note that the Variable type must be Variable<String?>, as text is an optional String in UIKit.

Upvotes: 5

Related Questions