码迷,mamicode.com
首页 > 其他好文 > 详细

MVVM实战

时间:2015-07-28 17:58:50      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

1.层次依赖

- (UIViewController *)createInitialViewController {
    self.viewModelServices = [RWTViewModelServicesImpl new];
    self.viewModel = [[RWTFlickrSearchViewModel alloc] initWithServices:self.viewModelServices];
    return [[RWTFlickrSearchViewController alloc] initWithViewModel:self.viewModel];
}

2.数据绑定(View-->ViewModel,在VC的ViewDidLoad时调用)

- (void)bindViewModel
{
    self.title = self.viewModel.title;
    RAC(self.viewModel, searchText) = self.searchTextField.rac_textSignal;
   self.searchButton.rac_command = self.viewModel.executeSearch; //绑定ViewModel中创建的RACComand
    RAC([UIApplication sharedApplication], networkActivityIndicatorVisible) = self.viewModel.executeSearch.executing;
    RAC(self.loadingIndicator, hidden) = [self.viewModel.executeSearch.executing not];
    [self.viewModel.executeSearch.executionSignals subscribeNext:^(id x) {
        [self.searchTextField resignFirstResponder];
    }];

}

3.数据绑定(ViewModel-->Other,在ViewModel初始化时调用)

- (void)initialize
{
    self.title = @"Flickr Search";

    RACSignal *validSearchSignal =
    [[RACObserve(self, searchText)
      map:^id(NSString *text) {
        return @(text.length > 3);
    }]
     distinctUntilChanged];

    [validSearchSignal subscribeNext:^(id x) {
        NSLog(@"search text is valid %@", x);
    }];
}

4.异步接口(Model层的服务接口)

- (RACSignal *)signalFromAPIMethod:(NSString *)method arguments:(NSDictionary *)args transform:(id (^)(NSDictionary *response))block
{
    // 1. 创建请求信号
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {

        // 2. 创建一个Flick请求对象
        OFFlickrAPIRequest *flickrRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext:self.flickrContext];
        flickrRequest.delegate = self;
        [self.requests addObject:flickrRequest];

        // 3. 从代理方法中创建一个信号
        RACSignal *successSignal = [self rac_signalForSelector:@selector(flickrAPIRequest:didCompleteWithResponse:)
                                                  fromProtocol:@protocol(OFFlickrAPIRequestDelegate)];

        // 4. 处理响应
        [[[successSignal
         map:^id(RACTuple *tuple) {
             return tuple.second;
         }]
         map:block]
         subscribeNext:^(id x) {
             [subscriber sendNext:x];
             [subscriber sendCompleted];
         }];

        // 5. 开始请求
        [flickrRequest callAPIMethodWithGET:method arguments:args];

        // 6. 完成后,移除请求的引用
        return [RACDisposable disposableWithBlock:^{
            [self.requests removeObject:flickrRequest];
        }];
    }];
}

 

MVVM实战

标签:

原文地址:http://www.cnblogs.com/guoxiaoqian/p/4683094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!