7

I have a UITableViewCell that contain a UISwitch. This cell has its own SwitchCellViewModel. Lets say it contains some Bool value (enabled vs disabled). And ViewController is the one who contains UITableView, creates viewModel for the cell and sets cell with it.

I want to a achieve:

  1. On a cell level: change UISwitch state whenever a viewModel’s bool property value changes (without reloading tableView of course).
  2. On a ViewController level: handle UISwitch state change (by user).

The use case is next: cell shows some option that can be disabled or enabled. That action goes to backend, and after I receive response with a result (enabled vs disabled on backend), I have to sync view’s state again with the updated data.

I understand how to subscribe to a property value change on a cell level, so when I change it in viewModel from viewController, it updates a cell view right away. But I’m not sure how to deal with back action from UISwitch to viewController.

Is it achievable with a single @Published bool property in viewModel, or I have to have 2 separate things for this bidirectional case.

It looks really silly to me that I have to expose a separate Publisher for this purpose, since I already have a @Published property in viewmodel, that view controller should be notified about, so why wouldn’t I use it. But if I use just one, then it will be the case that ViewController sets @Published var in viewModel, cell itself will handle it and adjust UI, but ViewController immediately gets event about it as well, since it is subscribed to on it.

Stas Ivanov
  • 917
  • 1
  • 10
  • 22
  • Why would you need a `@Published`? Do you plan to interact with SwiftUI? If yes, can you give us some more details? If not, then you might not the the SwiftUI property wrappers at all. – Cristik Mar 17 '21 at 23:13

1 Answers1

1

@Published is a one-way data flow - it, along with ObservableObject, synthesize a combine publisher chain that sends updates (half-duplex, or one-way) when the values "will change". It doesn't send the value that's changed, only a signal that something changed.

To get a data flow back to the model, you'll need to invoke something or trigger that back-data flow from UISwitch activating. It could be as simple as a callback method to update the model where you're keeping the state - and that's where I'd generally start.

heckj
  • 7,136
  • 3
  • 39
  • 50