I use the following UIViewController
and RxSwift/RxCocoa
based piece of code to write a very simply MVVM pattern to bind a UIButton
tap event to trigger some Observable
work and listen for the result:
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var someButton: UIButton!
var viewModel: ViewModel!
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
viewModel = ViewModel()
setupBindings()
}
private func setupBindings() {
someButton.rx.tap
.bind(to: self.viewModel.input.trigger)
.disposed(by: disposeBag)
viewModel.output.result
.subscribe(onNext: { element in
print("element is \(element)")
}).disposed(by: disposeBag)
}
}
class ViewModel {
struct Input {
let trigger: AnyObserver<Void>
}
struct Output {
let result: Observable<String>
}
let input: Input
let output: Output
private let triggerSubject = PublishSubject<Void>()
init() {
self.input = Input(trigger: triggerSubject.asObserver())
let resultObservable = triggerSubject.flatMap { Observable.just("TEST") }
self.output = Output(result: resultObservable)
}
}
It compiles and runs well. However, I need to Combin
ify this pattern with SwiftUI
, so I converted that code into the following:
import SwiftUI
import Combine
struct ContentView: View {
var viewModel: ViewModel
var subscriptions = Set<AnyCancellable>()
init(viewModel: ViewModel) {
self.viewModel = viewModel
setupBindings()
}
var body: some View {
Button(action: {
// <---- how to trigger viewModel's trigger from here
}, label: {
Text("Click Me")
})
}
private func setupBindings() {
self.viewModel.output.result.sink(receiveValue: { value in
print("value is \(value)")
})
.store(in: &subscriptions) // <--- doesn't compile due to immutability of ContentView
}
}
class ViewModel {
struct Input {
let trigger: AnySubscriber<Void, Never>
}
struct Output {
let result: AnyPublisher<String, Never>
}
let input: Input
let output: Output
private let triggerSubject = PassthroughSubject<Void, Never>()
init() {
self.input = Input(trigger: AnySubscriber(triggerSubject))
let resultPublisher = triggerSubject
.flatMap { Just("TEST") }
.eraseToAnyPublisher()
self.output = Output(result: resultPublisher)
}
}
This sample doesn't compile due to two errors (commented in code):
(1) Problem 1: How to trigger the publisher's work from the button's action closure like the case of RxSwift
above ?
(2) Problem 2 is related somehow to architectural design rather than a compile error:
the error says: ... Cannot pass immutable value as inout argument: 'self' is immutable ...
, that's because SwiftUI
views are structs, they are designed to be changed only through sorts of bindings (@State
, @ObservedObject
, etc ...), I have two sub-questions related to problem 2:
[A]: is it considered a bad practice to sink
a publisher in a SwiftUI
View ? which may need some workaround to store the cancellable
at the View
's struct scope ?
[B]: which one is better for SwiftUI/Combine
projects in terms of MVVM architectural pattern: using a ViewModel with [ Input[Subscribers], Output[AnyPublishers] ] pattern, or a
ObservableObject
ViewModel with [ @Published
properties] ?
ObservableObject
- it is native, simple, and automatically integrated with SwiftUI. – Workbag