swiftmvvmreactive-cocoareactive-cocoa-3

Observing mouse event in ViewModel Swift (Reactive Cocoa 3.0)


I'm trying to make a connection between my view and my viewModel using RAC 3.0. (Been reading Colin Eberhardt great tutorials on this) I want to subscribe to a Signal that fires every time func mouseUp(theEvent: NSEvent) is called. I.e.

func mouseUp(theEvent:NSEvent){
  //create some signal or pass a variable here to my viewModel
}

and then in my viewModel I would like to subscribe to that stream.

let signalFromview = MutableProperty<String>("")

signalFromView.observe(next: { println($0) })

But I can't get this to work. The only way I've managed to get this to work is to subscribe to a SignalProducer like so:

View:

func mouseUp(theEvent:NSEvent){
    viewModel.signalFromView.put(someValue)
}

ViewModel:

signalFromView.producer
|>start { println($0) }

But this isn't what I want since using the producer 'pulls' the value, i.e. upon first running this the code in the viewModel will be run on initialization with an empty value since it's trying to pull something that isn't there...

Hope this makes sense.


Solution

  • MutablePropertys should be used more like properties, and not as a proxy to a signal. So it should be initialized with a sensible initial value so that anyone that observes it via the producer will get values that make sense.

    If you want a Signal, you can set up the signal with something like this:

    let (signal, sink) = Signal<String, NoError>.pipe()
    

    In your mouseUp function, you'd send events using something like:

    sendNext(sink, someValue)
    

    And you'd observe using:

    signal.observe(next: { println($0) })