CleanArchitectureRxSwift icon indicating copy to clipboard operation
CleanArchitectureRxSwift copied to clipboard

ViewModelType protocol and associatedtype limitations

Open IvanKalaica opened this issue 6 years ago • 4 comments

Should't PostsViewModel be an protocol and not class? I think keeping protocol oriented view models is better than enforcing generic structure with associatedtype. Input/output transform can always be enforced per viewModel protocol. Thoughts?

IvanKalaica avatar Jan 11 '18 21:01 IvanKalaica

Hi, @IvanKalaica, thanks for the question :)

What benefits do you think we would get from using protocol? The only thing that comes to mind is snapshot and UITests.

Input/output transform can always be enforced per viewModel protocol.

Curious to see an example :)

sergdort avatar Feb 04 '18 23:02 sergdort

I think interface based programming is always a good habit. :)

struct ExampleViewModelInput {
    
}

struct ExampleViewModelOutput {
    let speedInKmh: Observable<Int>
}

protocol ExampleViewModel {
    func transform(input: ExampleViewModelInput) -> ExampleViewModelOutput
}

final class DefaultExampleViewModel: ExampleViewModel {
    private let exampleService: ExampleService
    
    init(exampleService: VehicleService) {
        self.exampleService = exampleService
    }
}

extension DefaultExampleViewModel {
    func transform(input: ExampleViewModelInput) -> ExampleViewModelOutput {    
        return ExampleViewModelOutput(
            speedInKmh: self.exampleService.map { $0.speedInKmh }.distinctUntilChanged()
        )
    }
}

IvanKalaica avatar Feb 05 '18 08:02 IvanKalaica

@IvanKalaica Could you explain more why the below code is good habit?

ttkien avatar Feb 25 '18 16:02 ttkien

@sergdort as per Dependency Inversion Principle (DIP) when 2 classes or modules are communicating with each other than both should link to abstraction rather than knowing about concrete module/class, which makes the system loosely coupled.

hr147 avatar Jan 22 '19 13:01 hr147