-
Notifications
You must be signed in to change notification settings - Fork 1
/
MYSDeferred.m
124 lines (105 loc) · 2.7 KB
/
MYSDeferred.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//
// FHSPromise.m
// Firehose
//
// Created by Adam Kirk on 2/22/14.
// Copyright (c) 2014 Mysterious Trousers. All rights reserved.
//
#import "MYSDeferred.h"
@interface MYSDeferred ()
@property (nonatomic, assign) FHSPromiseState state;
@property (nonatomic, copy ) NSMutableArray *alwaysHandlers;
@property (nonatomic, copy ) NSMutableArray *doneHandlers;
@property (nonatomic, copy ) NSMutableArray *failHandlers;
@end
@implementation MYSDeferred
- (id)init
{
self = [super init];
if (self) {
_state = FHSPromiseStatePending;
_alwaysHandlers = [NSMutableArray new];
_doneHandlers = [NSMutableArray new];
_failHandlers = [NSMutableArray new];
}
return self;
}
+ (instancetype)sharedDeferrerForActionName:(NSString *)actionName
{
static NSMutableDictionary *__deferrers;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__deferrers = [NSMutableDictionary new];
});
if (!__deferrers[actionName]) {
__deferrers[actionName] = [MYSDeferred new];
}
return __deferrers[actionName];
}
- (MYSDeferred *)always:(FHSPromiseHandler)handler
{
if (handler) {
if (self.state == FHSPromiseStateRejected || self.state == FHSPromiseStateResolved) {
handler();
}
else {
[self.alwaysHandlers addObject:handler];
}
}
return self;
}
- (MYSDeferred *)done:(FHSPromiseHandler)handler
{
if (handler) {
if (self.state == FHSPromiseStateResolved) {
handler();
}
else {
[self.doneHandlers addObject:handler];
}
}
return self;
}
- (MYSDeferred *)fail:(FHSPromiseHandler)handler
{
if (handler) {
if (self.state == FHSPromiseStateRejected) {
handler();
}
else {
[self.failHandlers addObject:handler];
}
}
return self;
}
//- (FHSPromise *)then:(void (^)(id object))handler
//{
// return self;
//}
//- (FHSPromise *)progress:(void (^)(id object))handler
//{
//
//}
//- (FHSPromise *)notify:(void (^)(id object))handler
//{
//
//}
- (void)reject
{
self.state = FHSPromiseStateRejected;
for (FHSPromiseHandler handler in [self.failHandlers arrayByAddingObjectsFromArray:self.alwaysHandlers]) {
handler();
[self.failHandlers removeObject:handler];
[self.alwaysHandlers removeObject:handler];
}
}
- (void)resolve
{
self.state = FHSPromiseStateResolved;
for (FHSPromiseHandler handler in [self.doneHandlers arrayByAddingObjectsFromArray:self.alwaysHandlers]) {
handler();
[self.doneHandlers removeObject:handler];
[self.alwaysHandlers removeObject:handler];
}
}
@end