VIPER architecture using RxSwift

As previously this function makes a network call and fetch movies data.Presenter also has a reference of ‘InterectorToPresenterSubject’//Interactorvar InterectorToPresenterSubject: PublishSubject<Void>?InterectorToPresenterSubject is again subscribed by the Presenter.//Presenterfunc subscribeToVariable(_ subject: PublishSubject<Void>) { subject.subscribe(onNext: { (event) in self.loadMoviesFinished() }), onError: { self.loadMoviesFailed() }), onCompleted: { print("completed") }) .disposed(by: disposeBag)}if the network call successfully have fetched the movies data it calls onNext event on the subject.InterectorToPresenterSubject.onNext(())and if it errors outInterectorToPresenterSubject.onError(ToPresenterError.error)Error can be defined as an enum extending from Errorpublic enum ToPresenterError: Error { case error}when ‘InterectorToPresenterSubject.onError’ is called the onError block in subscription is called, which is calling loadMoviesFailed() function.Finally Presenter has reference for PresenterToViewProtocol and View becomes subscriber for it.// View func subscribeToVariable(_ subject: PublishSubject<Void>) { subject.subscribe(onNext: { (event) in self.reloadTableViewData() }), onError: { self.showError() }), onCompleted: { print("completed") }) .disposed(by: disposeBag)}OnError event is fired from loadMoviesFailed() function of Presenter and onNext is fired from loadMoviesFinished function of Presenter.func loadMoviesFinished() { PresenterToViewSubject.onNext(())}func loadMoviesFailed() { PresenterToViewSubject.onError(ToPresenterError.error)}In every subscription there is a disposed function as well, it will dispose of the subscription using a dispose bag, when the respective class is deinitilized the subscription is automatically disposed of. In this way subscriber will not leak memory.ConclusionJust like any other design pattern VIPER is self-explanatory. One needs to get one’s hands dirty to understand the whole picture. My advice will be to first start with creating a very basic app with VIPER architecture, and then follow the steps explained above to convert the protocol implementation to RxSwift Observables.Happy coding :). More details

Leave a Reply