搜索框或者UITextField使用ReactiveCocoa

274 阅读1分钟

有时候我们使用搜索框或者UITextField,要在输入的时候进行处理,或者请求数据,但是不能马上请求,在要停止输入一段时间之后再进行请求,不然会浪费资源去一直请求数据。这个时候使用ReactiveCocoa再适合不过。

[[[[[[[self requestAccessToTwitterSignal]
      then:^RACSignal * _Nonnull{
          @strongify(self)
          return self.searchText.rac_textSignal;
      }]
      filter:^BOOL(NSString * text) {
          @strongify(self)
          return [self isValidSearchText:text];
      }] throttle:0.5]
      flattenMap:^__kindof RACSignal * _Nullable(NSString * text) {
          @strongify(self)
          return [self signalForSearchWithText:text];
      }] deliverOn:[RACScheduler mainThreadScheduler]]
     subscribeNext:^(NSDictionary *jsonSearchResult) {
         NSLog(@"access granted %@",jsonSearchResult);
         NSArray *statuses = jsonSearchResult[@"statuses"];
         NSArray *tweets = [statuses linq_select:^id(id tweet) {
             
             return [RWTweet tweetWithStatus:tweet];
         }];
         [self.resultsViewController displayTweets:tweets];
         
     } error:^(NSError * _Nullable error) {
         NSLog(@"access error is %@",error);
     }];

其中的throttle就是等待0.5秒没有变化就会起作用。