Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bindable protocol #37

Open
moto0000 opened this issue Jan 9, 2018 · 2 comments
Open

Bindable protocol #37

moto0000 opened this issue Jan 9, 2018 · 2 comments

Comments

@moto0000
Copy link

moto0000 commented Jan 9, 2018

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)
    }
}
@sergdort
Copy link
Owner

sergdort commented Feb 4, 2018

This is interesting approach 👍

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

@ttkien
Copy link

ttkien commented Feb 25, 2018

Great approach!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants