I'm working on an iOS project with RxSwift and I use the MVVM with coordinators pattern.
Here my implementation:
ViewModel:
// MARK: - Private
private let showNextViewSubject = PublishSubject<Void>()
// MARK: - Inputs
var showNextView: AnyObserver<Void> {
return showNextViewSubject.asObserver()
}
// MARK: - Outputs
var didShowNextView: Observable<Void> {
return showNextViewSubject.asObservable()
}
ViewController:
private func bindButton() {
_ = button.rx.tap
.bind(to: viewModel.showNextView)
.disposed(by: disposeBag)
}
Coordinator:
self.viewModel.didShowNextView
.subscribe(onNext: { [weak self] _ in
self?.showNextView()
})
.disposed(by: disposeBag)
My problem is with the [weak self] _
in the coordinator: when I add it, self?.showNextView()
is never called, but this works well when I remove it.
Do you know why?
Thanks, Romain
I won’t go through the MVVM pattern from the ground up, but after you’ve read the series you’ll be able to use RxSwift with MVVM. In case you want to know the basics of MVVM pattern, I suggest that you check out my older post MVVM with Swift application.
RxSwift is the Swift version of the family ReactiveX —once you master it, you are able to switch easily to RxJava, RxJavascript and so on. This framework allows you to write functional reactive programming (FRP) and thanks to the internal library RxCocoa you are able to bind View and ViewModel easily:
MVVM is similar to the standard MVC, except it defines one new component — ViewModel, which allows to better decouple UI from the Model. Essentially, ViewModel is an object which represents View UIKit-independently. The example project is in the MVVM-Rx folder.
Essentially, ViewModel is an object which represents View UIKit-independently. The example project is in the MVVM-Rx folder. First, let’s create a View Model which will prepare the Model data for displaying in the View: Next, we will move all our data mutation and formatting code from the RepositoryListViewController into RepositoryListViewModel:
When you get rid of [weak self]
the block creates a strong reference to self
so that it's not deallocated when any other code is done using it. By making the reference weak self
is free to be deallocated which is probably happening. This means there is no other object with a strong reference to self
so it is nil and the call won't be made. Getting rid of it could create a retain cycle so you'll want to be careful of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With