Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveSwift - Updating Value Of MutableProperty?

As a followup to this question, which received this fantastic answer, and using the following example...

class Model {
    let mapType = MutableProperty<MKMapType>(.standard)
}

class SomeViewController: UIViewController {

    let viewModel: Model
    var mapView: MKMapView!

    init(viewModel: Model) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView = // Create the map view
        viewModel.mapType.producer.startWithValues { [weak self] mapType in
            self?.mapView.mapType = mapType
        }
        // Rest of bindings
    }
    // The rest of the implementation...
}

class SomeOtherViewController: UIViewController {

    let viewModel: Model
    var segmentedControl: UISegmentedControl!

    init(viewModel: Model) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
        // Pretend we've setup the segmentedControl, and set its action to `updateMap(sender:)`...
        // The rest of the initialization...
    }

    func updateMap(sender: UISegmentedControl) {
        let newMapType =...
        self.viewModel.mapType = newMapType // How do I update this value?
    }
    // The rest of the implementation...
}

How can I update the value of Model.mapType, and have its changes sent to any observers (like SomeViewController in the example)?

like image 753
forgot Avatar asked Feb 06 '23 12:02

forgot


1 Answers

You just need to set its value property, this will trigger changes to be sent to observers automatically.

self.viewModel.mapType.value = newMapType

like image 179
Charles Maria Avatar answered Mar 05 '23 05:03

Charles Maria