Skip to content

Commit 1428415

Browse files
committed
Support multiple state subscriptions.
1 parent e35d5ed commit 1428415

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

STNetTaskQueue/STNetTask.m

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ @interface STNetTask ()
1616
@property (atomic, assign) BOOL cancelled;
1717
@property (atomic, assign) BOOL finished;
1818
@property (atomic, assign) NSUInteger retryCount;
19-
@property (nonatomic, strong) NSMutableDictionary *stateToBlock;
19+
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSMutableArray *> *stateToBlock;
2020

2121
@end
2222

@@ -58,22 +58,37 @@ - (NSTimeInterval)retryInterval
5858
}
5959

6060
- (void)subscribeState:(STNetTaskState)state usingBlock:(STNetTaskSubscriptionBlock)block
61+
{
62+
if ([NSThread isMainThread]) {
63+
[self _subscribeState:state usingBlock:block];
64+
}
65+
else {
66+
dispatch_async(dispatch_get_main_queue(), ^{
67+
[self _subscribeState:state usingBlock:block];
68+
});
69+
}
70+
}
71+
72+
- (void)_subscribeState:(STNetTaskState)state usingBlock:(STNetTaskSubscriptionBlock)block
6173
{
6274
if (!self.stateToBlock) {
6375
self.stateToBlock = [NSMutableDictionary new];
6476
}
65-
NSAssert(self.stateToBlock[@(state)] == nil, @"State is subscribed already");
66-
self.stateToBlock[@(state)] = [block copy];
77+
NSMutableArray *blocks = self.stateToBlock[@(state)];
78+
if (!blocks) {
79+
blocks = [NSMutableArray new];
80+
self.stateToBlock[@(state)] = blocks;
81+
}
82+
[blocks addObject:[block copy]];
6783
}
6884

6985
- (void)notifyState:(STNetTaskState)state
7086
{
7187
dispatch_async(dispatch_get_main_queue(), ^{
72-
STNetTaskSubscriptionBlock block = self.stateToBlock[@(state)];
73-
if (block) {
88+
NSArray *blocks = self.stateToBlock[@(state)];
89+
for (STNetTaskSubscriptionBlock block in blocks) {
7490
block();
7591
}
76-
7792
switch (state) {
7893
case STNetTaskStateFinished:
7994
case STNetTaskStateCancalled: {

STNetTaskQueueTest/STNetTaskQueueTest/STNetTaskQueueTestHTTP.m

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,14 @@ - (void)testSubscriptionBlock
193193
STTestGetNetTask *testGetTask = [STTestGetNetTask new];
194194
testGetTask.id = 1;
195195
[[STNetTaskQueue sharedQueue] addTask:testGetTask];
196-
196+
197+
__block NSUInteger subscriptionCalled = 0;
198+
[testGetTask subscribeState:STNetTaskStateFinished usingBlock:^{
199+
subscriptionCalled++;
200+
}];
197201
[testGetTask subscribeState:STNetTaskStateFinished usingBlock:^{
198-
if (testGetTask.finished) {
202+
subscriptionCalled++;
203+
if (testGetTask.finished && subscriptionCalled == 2) {
199204
[_expectation fulfill];
200205
}
201206
else {

0 commit comments

Comments
 (0)