有時候我們使用搜尋框或者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秒沒有變化就會起作用。