forked from peter-iakovlev/Signals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSignal+Accumulate.m
52 lines (45 loc) · 1.36 KB
/
SSignal+Accumulate.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#import "SSignal+Accumulate.h"
@implementation SSignal (Accumulate)
- (SSignal *)reduceLeft:(id)value with:(id (^)(id, id))f
{
return [[SSignal alloc] initWithGenerator:^(SSubscriber *subscriber)
{
__block id intermediateResult = value;
return [self startWithNext:^(id next)
{
intermediateResult = f(intermediateResult, next);
} error:^(id error)
{
[subscriber putError:error];
} completed:^
{
if (intermediateResult != nil)
[subscriber putNext:intermediateResult];
[subscriber putCompletion];
}];
}];
}
- (SSignal *)reduceLeftWithPassthrough:(id)value with:(id (^)(id, id, void (^)(id)))f
{
return [[SSignal alloc] initWithGenerator:^(SSubscriber *subscriber)
{
__block id intermediateResult = value;
void (^emit)(id) = ^(id next)
{
[subscriber putNext:next];
};
return [self startWithNext:^(id next)
{
intermediateResult = f(intermediateResult, next, emit);
} error:^(id error)
{
[subscriber putError:error];
} completed:^
{
if (intermediateResult != nil)
[subscriber putNext:intermediateResult];
[subscriber putCompletion];
}];
}];
}
@end