RAC(ReactiveCocoa)使用方法(二)

ptlCoder發表於2018-01-23

RAC(ReactiveCocoa)使用方法(一) RAC(ReactiveCocoa)使用方法(二)

上篇文章:RAC(ReactiveCocoa)使用方法(一) 中主要介紹了一些RAC中常見類的用法,這篇文章主要總結日常開發中結合一些UI控制元件的用法。 RAC給常見的很多UI類擴充了用法,使得開發變得越來越簡單,減少了很多不必要的代理和Target程式碼,RAC內部已經處理好了這些事件。

網路請求

貼上核心程式碼,具體程式碼見Github;

//
//  ViewModel.m
//  
//
//  Created by soliloquy on 2017/11/28.
//

//豆瓣電影API
#define url @"https://api.douban.com/v2/movie/in_theaters?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&start=0&count=100&client=&udid="

#import "ViewModel.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "Model.h"


@implementation ViewModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        __weak typeof (self)weakSelf = self;
        self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                
                [weakSelf fetchData:^(NSArray *arr) {
                    [subscriber sendNext:arr];
                    [subscriber sendCompleted];
                } failure:^(NSError *error) {
                    [subscriber sendError:error];
                }];
                
                return nil;
            }];
        }];
        
    }
    return self;
}

- (void)fetchData:(void(^)(NSArray *arr))successBlock failure:(void(^)(NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = [Model mj_objectArrayWithKeyValuesArray:responseObject[@"subjects"]];
        /** 方法一:block回撥出去
        if (self.dataSourceBlock) {
            self.dataSourceBlock(arr);
        }
         */
        /**
            方法二 : ReactiveCocoa
         */
        
        if (successBlock) {
            successBlock(arr);
        }


        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
}

@end

複製程式碼
- (void)viewDidLoad {
    [super viewDidLoad];

  [self bindViewModel];
}

- (void)bindViewModel {
      /** RAC */
    @weakify(self)
    [self.viewModel.command.executionSignals.switchToLatest  subscribeNext:^(NSArray *dataSource) {
        @strongify(self);
        self.dataSource = dataSource;
        
        NSLog(@"%@",dataSource);
    }];

    // 返回錯誤
    [self.viewModel.command.errors subscribeNext:^(NSError *_Nullable x) {
        NSLog(@"-- error : %@", x.description);
    }];
    
    //執行command
    [self.viewModel.command execute:nil];
}
複製程式碼

代理

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"標題" message:@"123456" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"other", nil];
[[self rac_signalForSelector:@selector(alertView:clickedButtonAtIndex:) fromProtocol:@protocol(UIAlertViewDelegate)] subscribeNext:^(RACTuple *tuple) {
    NSLog(@"%@",tuple.first);
    NSLog(@"%@",tuple.second);
    NSLog(@"%@",tuple.third);
}];
[alertView show];
複製程式碼

通知

  • 傳送通知
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"notiName" object:dataArray];
複製程式碼
  • 接收通知
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"notiName" object:nil] subscribeNext:^(NSNotification *notification) {
    NSLog(@"%@", notification.name);
    NSLog(@"%@", notification.object);
}];
複製程式碼

KVO

    UIScrollView *scrolView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    scrolView.contentSize = CGSizeMake(200, 800);
    scrolView.backgroundColor = [UIColor redColor];
    [self.view addSubview:scrolView];
    [RACObserve(scrolView, contentOffset) subscribeNext:^(id x) {
        NSLog(@"contentOffset: %@",x);
    }];
複製程式碼

####Target-Action

  • UIButton
[[self.button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        NSLog(@"x:%@", x);
    }];
複製程式碼
  • UITextField
[self.tf.rac_textSignal subscribeNext:^(id x) {
         NSLog(@"x:%@", x);
        self.label.text = x;
    }];
複製程式碼
[[self.tf.rac_textSignal map:^id(id value) {
        return [UIColor redColor];
    }] subscribeNext:^(id x) {
//        NSLog(@"x:%@", x);
    }];
複製程式碼
  • UIView
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    [tap.rac_gestureSignal subscribeNext:^(id x) {
       NSLog(@"x:%@", x);
        self.redView.backgroundColor = [UIColor yellowColor];
    }];
    [self.redView addGestureRecognizer: tap];
複製程式碼

詳情見github.

相關文章