sergdort / CleanArchitectureRxSwift

Example of Clean Architecture of iOS app using RxSwift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bindable protocol

moto0000 opened this issue · comments

Hi,
What do you think about the introduction of BindableType protocol?

protocol BindableType {
    associatedtype ViewModel: ViewModelType

    var viewModel: ViewModel { get }

    func bindInput() -> ViewModel.Input
    func bind(output: ViewModel.Output)
}

extension BindableType {

    func bindViewModel() {
        let input = bindInput()
        let output = viewModel.transform(input: input)
        bind(output: output)
    }
}

Example:

import RxSwift
import RxCocoa

class ViewModel: ViewModelType {

    struct Input {
        let trigger: Driver<Void>
    }

    struct Output {
        let value: Driver<Void>
    }

    func transform(input: Input) -> Output {
        return Output(value: input.trigger)
    }
}

class ViewController: UIViewController, BindableType {
    
    let viewModel: ViewModel
    private let disposeBag = DisposeBag()

    init(viewModel: ViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        bindViewModel()
    }

    func bindInput() -> ViewModel.Input {
        return ViewModel.Input(trigger: .just(()))
    }

    func bind(output: ViewModel.Output) {
        output.value
            .drive()
            .disposed(by: disposeBag)
    }
}

This is interesting approach 👍

My concern tho is that it makes ViewModel public in the ViewController right?

Great approach!