图片.png
主要在于 ViewModel
ViewModel: 相比较于MVC新引入的视图模型。是视图显示逻辑、验证逻辑、网络请求等代码存放的地方,唯一要注意的是,任何视图本身的引用都不应该放在VM中,换句话说就是VM中不要引入UIKit.h (对于image这个,也有人将其看做数据来处理,这就看个人想法了,并不影响整体的架构)。
比如一个用户登录网络请求,将网络请求相关逻辑都放到viewModel中执行
@interface GHLoginViewModel : NSObject
@property (nonatomic, strong) RACCommand *loginCommand;
@property (nonatomic, strong) RACCommand *refreshTokenCommand;
@interface GHLoginRequest : GHNetworkBaseRequest
/// 手机号\邮箱
@property (nonatomic, copy) NSString *username;
/// 密码(密码由 8 - 128 字符组成,不能为纯数字或字母)
@property (nonatomic, copy) NSString *password;
/// 国家码简称
@property (nonatomic, copy) NSString *region_code;
/// 手机号国家码
@property (nonatomic, copy) NSNumber *phone_code;
@end
@implementation GHLoginViewModel
- (instancetype)init
{
self = [super init];
if (self) {
}
return self;
}
- (RACCommand *)loginCommand {
if (!_loginCommand) {
_loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(GHLoginRequest* _Nullable input) {
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
NSString *taskId = [GHNetworkModule.share sendRequest:input cacheComplete:nil networkComplete:^(GHNetworkResponse *response) {
if (response.status == GHNetworkResponseStatusSuccess) {
GHUserInfo.share.password = input.password;
GHUserInfo.share.token = response.data[@"token"];
[subscriber sendNext:response.data];
[subscriber sendCompleted];
[GHUserInfo cacheInfo];
} else {
[subscriber sendError:response.error];
}
}];
return [RACDisposable disposableWithBlock:^{
[GHNetworkModule.share cancelRequestWithRequestID:taskId];
}];
}];
}];
}
return _loginCommand;
}
在viewcontoller中接收请求结果
//返回数据处理
[self.viewModel.loginCommand.executionSignals.switchToLatest subscribeNext:^(id _Nullable x) {
@strongify(self)
[GHHudTip hideHUDWithView:self.view];
}];
//异常处理
[self.viewModel.loginCommand.errors subscribeNext:^(NSError * _Nullable x) {
@strongify(self)
[GHHudTip hideHUDWithView:self.view];
[GHHudTip showTips:x.domain];
}];
延伸与扩展:iOS MVVM+RAC 从框架到实战
结语:RAC的功能非常强大,且实用。这里只是列举了一小部分。其他还需要我们在开发中慢慢发掘。加油~

评论列表