Skip to content

Chapter 2. Drive.

Dmitriy Shulzhenko edited this page Sep 27, 2020 · 25 revisions

I use “drivers” to define and manipulate state. It can be a shared app component state or a simple view state. Equivalent to ViewModel in well known MVVM.

import RxSwift
import RxCocoa

protocol MovieDetailDriving {
    var data: Driver<MovieDetailData> { get }
    var didClose: Driver<Void> { get }
    
    func close()
}
final class MovieDetailDriver: MovieDetailDriving {
    private let closeRelay = PublishRelay<Void>()
    
    private let id: Int
    private let api: TMDBApiProvider
    
    var data: Driver<MovieDetailData> {
        api.fetchMovieDetails(forMovieId: id)
            .unwrap()
            .compactMap(MovieDetailData.init)
            .asDriver()
    }
    
    var didClose: Driver<Void> { closeRelay.asDriver() }
    
    init(id: Int, api: TMDBApiProvider) {
        self.id = id
        self.api = api
    }
    
    func close() {
        closeRelay.accept(())
    }
}

Next I will show how to bind our ViewController with the Driver.

Clone this wiki locally