RxSwift Way To Map and Bind UITextView's Text to Custom Object's text field?

finneycanhelp picture finneycanhelp · Nov 25, 2015 · Viewed 7.3k times · Source

I know I can do the following to map changes to a custom object's Notes' text field to a UITextView.

self.notesViewModel.currentNote()
           .map { $0.text }
           .bindTo(self.notesTextView.rx_text)

How can I do the reverse using the same kind of pattern? The pattern is notesTextView.rx_text, map it to the current note's text. I know how to do the following which feels non-RxSwift-y:

_ = notesTextView.rx_text.subscribeNext { someText in
    self.notesViewModel.currentNote().value.text = someText
}

IOW, it seems like I should be able to take the UITextView (aka notesTextView), map, and bind changes into the current note. Current note returns a Variable with a Note having a text String field.

Answer

bontoJR picture bontoJR · Nov 28, 2015

You can use the <-> two way binding operator.

There's a nice example in the RxSwift repo, here's a usage example:

// bind UI values to variables
usernameOutlet.rx_text <-> username
passwordOutlet.rx_text <-> password
repeatedPasswordOutlet.rx_text <-> repeatedPassword