Signaling from a model point of view in MVVM using ReactiveCocoa 4

I am embedding ReactiveCocoa 4 in an as-basic-as-possible iOS app (Swift) in order to better understand how to use it with the MVVM architecture. My question is: how to get UITextField textSignal from view to model?

What works for me here, but it looks like it's only 50% reactive (and not too good anyway):

VIEW (in viewDidLoad)

originalTextField.rac_textSignal().subscribeNext{
    (next:AnyObject!) -> () in
    let text = next as! String
    self.viewModel?.originalText=text
}

VIEWING THE MODEL

var originalText:String?{
    didSet{self.model.originalText=originalText}
}

MODEL

var originalText:String?{
    didSet{//Do model stuff}
}
+4
source share
1 answer

This is how I currently implement this behavior, I'm pretty new to RAC, so grab it with salt.

I use ReactiveCocoa 4.1.0 & Rex 0.10.0


ViewModel

  • Set MutablePropertytooriginalText

Mutable properties producer, .

originalText.producer.startWithNext 1 , ViewModel

    let originalText: MutableProperty<String> = MutableProperty("")

    func observeTextField(){
        originalText.producer.startWithNext { (str) in
            self.model.originalText = str
        }
    }

Rex . ignoreError Rex .

SignalProducer SignalProducer<T, ErrorType>, ErrorType MutableProperty<String>.

  • .
  • ViewModel MutableProperty
  • ViewModel.observeTextField 3

infix <~ ViewModel MutableProperty

    import Rex

...

    let textFieldProducer = (originalTextField.rac_textSignal()
        .toSignalProducer()
        .map {text in text as! String}
        .ignoreError())!

    viewModelInstance.originalText <~ textFieldProducer

, .

0

Source: https://habr.com/ru/post/1614137/


All Articles