ReactiveCocoa信号(RACStream (Operations)文件中)操作像Swift里面的一些高阶函数一样有map,flattenMap,reduce, filter等操作。
1. map
(Returns a new stream with the mapped values.)
<pre>
[signale map:^id(id value) {
1⃣️
return [NSString stringWithFormat:@"输出:%@",value];2⃣️
}] subscribeNext:^(id x) {
NSLog(@"090909----->%@",x);3⃣️
}];
</pre>
其中:
1⃣️:传入一个block类型,返回id类型的对象,参数是value
2⃣️:value就是源信号的内容,直接拿到源信号的内容做处理。并返回相关id
3⃣️:x表示经过处理后的value值
2. flattenMap
(Returns a new stream which represents the combined streams resulting from mapping block
.)
<pre>
[signal flattenMap:^RACStream *(id value) {
1⃣️
return [RACSignal return:[NSString stringWithFormat:@"输出09090:%@",value]]; 2⃣️
}] subscribeNext:^(id x) {
NSLog(@"%@",x); 3⃣️
}];
]
</pre>
其中:
1⃣️:传入一个block,block类型是返回值RACStream,参数value
2⃣️:参数value就是源信号的内容,拿到源信号的内容做处理。注意这里返回的是一个RACStream信号类,不是id对象。
3⃣️:输出经过处理的value内容。
3. reduce
(Returns a signal which sends the results from each invocation of reduceBlock
.)
<pre>
RACSignal *signalA = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"A"];
[subscriber sendCompleted];
return nil;
}];
RACSignal *signalB = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"B"];
[subscriber sendCompleted];
return nil;
}];
RACSignal *reduceSignal = [RACSignal combineLatest:@[signalA,signalB] reduce:^id(NSString *x,NSString *y){
return [NSString stringWithFormat:@"%@ %@",x,y];
}];
[reduceSignal subscribeNext:^(id x) {
NSLog(@"%@",x); ---->A B
}];
</pre>
其中:
常见的用法,(先组合在聚合)。combineLatest:(id<NSFastEnumeration>)signals reduce:(id (^)())reduceBlock
reduce中的block简介:
reduceblcok中的参数,有多少信号组合,reduceblcok就有多少参数,每个参数就是之前信号发出的内容
reduceblcok的返回值:聚合信号之后的内容。
4. filter
Filters out values in the receiver that don't pass the given test. This corresponds to the Where
method in Rx.
Returns a new stream with only those values that passed.
过滤不符合要求的信号,返回符合要求的信号。
<pre>
[[textFiled.rac_textSignal filter:^BOOL(NSString *value) {
return value.length>3;
}] subscribeNext:^(id x) {
NSLog(@"%@",x);
}];
当输入框的内容长度>3时,才有输出。
</pre>