好長一段時間沒有敲簡書了!
主要是因為一直在跑面試。
終於還是在上海入職了!
由於項目原因最終還是入了MVVM+RAC的坑
下面是正題。
Demo效果
使用MVVM+RAC請求網絡數據
ReactiveCocoa簡介
在iOS開發過程中,當某些事件響應的時候,需要處理某些業務邏輯,這些事件都用不同的方式來處理。
比如按鈕的點擊使用action,ScrollView滾動使用delegate,屬性值改變使用KVO等系統提供的方式。
其實這些事件,都可以通過RAC處理
ReactiveCocoa為事件提供了很多處理方法,而且利用RAC處理事件很方便,可以把要處理的事情,和監聽的事情的代碼放在一起,這樣非常方便我們管理,就不需要跳到對應的方法里。非常符合我們開發中高聚合,低耦合的思想。
基礎的話我還是推薦這篇博文 講的都挺細的
當然不爽的話可以試試這個視頻版的,也是某培訓機構流出的
Demo分析
本文使用的是豆瓣API(非官方)
Demo所要做的功能很簡單: 從網絡中請求數據,並加載到UI上。
MVVM中最重要也就是這個VM了,VM通常與RAC緊密結合在一起,主要用於事務數據的處理和信號間的傳遞。
Demo中主要使用了下面這些第三方庫
pod 'SDWebImage'
pod 'Motis'
pod 'ReactiveCocoa', '2.5'
pod 'BlocksKit'
pod 'AFNetworking'
pod 'Masonry'
pod 'SVProgressHUD'
這里除了RAC 還有一個值得提一下
BlocksKit
眾所周知Block已被廣泛用於iOS編程。它們通常被用作可並發執行的邏輯單元的封裝,或者作為事件觸發的回調。Block比傳統回調函數有2點優勢:
- 允許在調用點上下文書寫執行邏輯,不用分離函數
- Block可以使用local variables.
基於以上種種優點Cocoa Touch越發支持Block式編程,這點從UIView的各種動畫效果可用Block實現就可以看出。而BlocksKit是對Cocoa Touch Block編程更進一步的支持,它簡化了Block編程,發揮Block的相關優勢,讓更多UIKit類支持Block式編程。
代碼
由於BlocksKit的使用,當我們寫Delegate和Datasource時 就不用分離函數,整個邏輯都能湊在一起,比如這樣定義一個collectionView:
- (void)initStyle {
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
collectionView.backgroundColor = [UIColor redColor];
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.showsVerticalScrollIndicator = NO;
collectionView.alwaysBounceVertical = YES;
[self.view addSubview:collectionView];
[collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.mas_topLayoutGuide);
make.left.right.equalTo(self.view);
make.bottom.equalTo(self.view.mas_bottom);
}];
self.collectionView = collectionView;
//注冊cell
[self.collectionView registerClass:[MovieCollectionViewCell class] forCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier]];
//collectionView dataSouce
A2DynamicDelegate *dataSouce = self.collectionView.bk_dynamicDataSource;
//item個數
[dataSouce implementMethod:@selector(collectionView:numberOfItemsInSection:) withBlock:^NSInteger(UICollectionView *collectionView, NSInteger section) {
return self.listArray.count;
}];
//item配置
[dataSouce implementMethod:@selector(collectionView:cellForItemAtIndexPath:) withBlock:^UICollectionViewCell*(UICollectionView *collectionView,NSIndexPath *indexPath) {
id<MovieModelProtocol> cell = nil;
Class cellClass = [MovieCollectionViewCell class];
if (cellClass) {
cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier] forIndexPath:indexPath];
if ([cell respondsToSelector:@selector(renderWithModel:)]) {
[cell renderWithModel:self.listArray[indexPath.row]];
}
}
return (UICollectionViewCell *)cell;
}];
self.collectionView.dataSource = (id)dataSouce;
#define scaledCellValue(value) ( floorf(CGRectGetWidth(collectionView.frame) / 375 * (value)) )
//collectionView delegate
A2DynamicDelegate *delegate = self.collectionView.bk_dynamicDelegate;
//item Size
[delegate implementMethod:@selector(collectionView:layout:sizeForItemAtIndexPath:) withBlock:^CGSize(UICollectionView *collectionView,UICollectionViewLayout *layout,NSIndexPath *indexPath) {
return CGSizeMake(scaledCellValue(100), scaledCellValue(120));
}];
//內邊距
[delegate implementMethod:@selector(collectionView:layout:insetForSectionAtIndex:) withBlock:^UIEdgeInsets(UICollectionView *collectionView ,UICollectionViewLayout *layout, NSInteger section) {
return UIEdgeInsetsMake(0, 15, 0, 15);
}];
self.collectionView.delegate = (id)delegate;
}
這就將所有有關collectionView的內容都包含在一起了,這樣更符合邏輯。
我們讓viewModel來處理網絡請求,controller需要做的就是啟動這個開關,並接受數據而已,所有的工作交給viewModel來處理
MovieViewModel.m
- (void)initViewModel {
@weakify(self);
self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
@strongify(self);
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
@strongify(self);
[self getDoubanList:^(NSArray<MovieModel *> *array) {
[subscriber sendNext:array];
[subscriber sendCompleted];
}];
return nil;
}];
}];
}
/**
網絡請求
@param succeedBlock 成功回調
*/
- (void)getDoubanList:(void(^)(NSArray<MovieModel*> *array))succeedBlock {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSMutableArray *array = [NSMutableArray array];
MoviewModelList *base = [[MoviewModelList alloc] init];
[base mts_setValuesForKeysWithDictionary:responseObject];
//遍歷數組取出 存入數組並回調出去
[base.subjects enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
MovieModel *model = [[MovieModel alloc] init];
[model mts_setValuesForKeysWithDictionary:obj];
[array addObject:model];
}];
if (succeedBlock) {
succeedBlock(array);
}
} failure:nil];
}
ViewController.m
- (void)bindViewModel {
@weakify(self);
//將命令執行后的數據交給controller
[self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(NSArray<MovieModel *> *array) {
@strongify(self);
[SVProgressHUD showSuccessWithStatus:@"加載成功"];
self.listArray = array;
[self.collectionView reloadData];
[SVProgressHUD dismissWithDelay:1.5];
}];
//執行command
[self.viewModel.command execute:nil];
[SVProgressHUD showWithStatus:@"加載中..."];
}