Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM-C with RxSwift: '[weak self]' in closure

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

like image 945
vermotr Avatar asked Jul 18 '18 06:07

vermotr


People also ask

Can I use rxswift with MVVM?

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.

What is the use of rxswift?

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:

What is MVVM-RX?

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.

What is a ViewModel in MVVM?

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:


1 Answers

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.

like image 171
Joe Avatar answered Sep 30 '22 18:09

Joe