ReactiveX / RxSwift

Reactive Programming in Swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Set initial value for UISwitch

Serg-Pogrebnyak opened this issue · comments

How I can set initial value for UISwitch and received it via switch.rx.isOn?
Now I hardcoded in next way:
switch.isOn = state
switch.sendActions(for: .valueChanged)

But this solution looks ugly, does exist a better solution?

You are treating your view as if it was a model. Don't do that. You should have an Observable<Bool> that represents the state of the switch. The switch should observe this; anything else that needs to know the state of the switch should also observe it.

Note that if you were using @IBActions, you would be having the same problem.

yeah, I know... But when my view is starting I want to set the initial value from UserDefaults (for example), and like output I use: Observable<Bool> { self.switch.rx.isOn }.

And in my case, I didn't receive any data when I set the initial value.

p.s. No race condition here. At first, I create a view and subscribe on listening to switch value change and after this, I set the initial state for my switch.

You tell me you receive data from UserDefaults and then tell you didn't receive any data. I'm not sure how to take that.

If you are receiving data from two different sources, then merge the sources. That then becomes the Observable that the switch observes.

UserDefaults - it's just an example, you can receive this data from the server.
Main question it's how I can change isOn value of switch programmatically and receive this update via next observable - Observable<Bool> { self.switch.rx.isOn }?

You are already doing that in the code you posted. Yes, UserDefaults was just an example, but no matter what other example you give, the answer is the same.
The fundamental problem is that you are still thinking imperatively; you want to go in and manually change the switch state without updating your model. Your switch state is supposed to be a reflection of the model.

Okay, I think I got you... Thanks🙃