iOS Combine - toant-dev/toandev.github.io GitHub Wiki

PassthroughSubject vs. CurrentValueSubject?

The main difference between both subjects is that a PassthroughSubject doesn’t have an initial value or a reference to the most recently published element. Therefore, new subscribers will only receive newly emitted events.

PassthroughSubject<State, Error>()

CurrentValueSubject<State, Error>(.pending)

  • A PassthroughSubject is like a doorbell push button. When someone rings the bell, you’re only notified when you’re at home
  • A CurrentValueSubject is like a light switch. When a light is turned on while you’re away, you’ll still notice it was turned on when you get back home.

Using Combine with MVVM

The Combine framework is perfectly suitable to work in combination with MVVM.

final class FormViewModel {
    @Published var isSubmitAllowed: Bool = false
}

final class FormViewController: UIViewController {
 
    private var switchSubscriber: AnyCancellable?
    private var viewModel = FormViewModel()

    @IBOutlet private weak var acceptTermsSwitch: UISwitch!
    @IBOutlet private weak var submitButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        switchSubscriber = viewModel.$isSubmitAllowed
            .receive(on: DispatchQueue.main)
            .assign(to: \.isEnabled, on: submitButton)
    }

    @IBAction func didSwitch(_ sender: UISwitch) {
        viewModel.isSubmitAllowed = sender.isOn
    }
}