![1306450-e481e2c5cbc0b28d.png](https://i-blog.csdnimg.cn/blog_migrate/cc86060bccb82022058ca4f4ab2df243.webp?x-image-process=image/format,png)
ViewModel需要具备以下特性:
- 可插拔;
- 可测试;
- 采用绑定机制的MVVM模式会更加强大,所以ViewModel要充分利用RxSwift;
把ViewModel当做黑箱,它可以接收输入,并产生输出,这就是定义ViewModel最好的原则。
方案一 (不采用Subjects
)
定义ViewModelType协议
protocol ViewModelType {
associatedtype Input
associatedtype Output
func transform(input: Input) -> Output
}
这种方案简单易行,只需要一次性提供Input给ViewModel,然后ViewModel即可给出Output。
让我们创建示例Demo:
输入内容,然后点击Validate按钮。最后,显示校验结果。
![1306450-3875b31692d1bd15.gif](https://i-blog.csdnimg.cn/blog_migrate/9e7771f8fa5c0184e9f43f04ab172173.webp?x-image-process=image/format,png)
创建SayHelloViewModel,它需要知道输入的文本以及按钮点击事件,这就是Input。
然后Output是文本内容。
final class SayHelloViewModel: ViewModelType {
struct Input {
let name: Observable<String>
let validate: Observable<Void>
}
struct Output {
let greeting: Driver<String>
}
func transform(input: Input) -> Outpu