-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSTNetTask.m
More file actions
104 lines (84 loc) · 2.05 KB
/
STNetTask.m
File metadata and controls
104 lines (84 loc) · 2.05 KB
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
//
// STNetTask.m
// STNetTaskQueue
//
// Created by Kevin Lin on 29/11/14.
// Copyright (c) 2014 Sth4Me. All rights reserved.
//
#import "STNetTask.h"
NSString *const STNetTaskUnknownError = @"STNetTaskUnknownError";
@interface STNetTask ()
@property (atomic, assign) BOOL pending;
@property (atomic, assign) BOOL cancelled;
@property (atomic, assign) BOOL finished;
@property (atomic, assign) NSUInteger retryCount;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSMutableArray<STNetTaskSubscriptionBlock> *> *stateToBlock;
@end
@implementation STNetTask
- (NSString *)uri
{
return @"";
}
- (void)didResponse:(id)response
{
}
- (void)didFail
{
}
- (void)didRetry
{
}
- (NSUInteger)maxRetryCount
{
return 0;
}
- (BOOL)shouldRetryForError:(NSError *)error
{
return YES;
}
- (NSTimeInterval)retryInterval
{
return 0;
}
- (void)subscribeState:(STNetTaskState)state usingBlock:(STNetTaskSubscriptionBlock)block
{
if ([NSThread isMainThread]) {
[self _subscribeState:state usingBlock:block];
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self _subscribeState:state usingBlock:block];
});
}
}
- (void)_subscribeState:(STNetTaskState)state usingBlock:(STNetTaskSubscriptionBlock)block
{
if (!self.stateToBlock) {
self.stateToBlock = [NSMutableDictionary new];
}
NSMutableArray *blocks = self.stateToBlock[@(state)];
if (!blocks) {
blocks = [NSMutableArray new];
self.stateToBlock[@(state)] = blocks;
}
[blocks addObject:[block copy]];
}
- (void)notifyState:(STNetTaskState)state
{
dispatch_async(dispatch_get_main_queue(), ^{
NSArray *blocks = self.stateToBlock[@(state)];
for (STNetTaskSubscriptionBlock block in blocks) {
block();
}
switch (state) {
case STNetTaskStateFinished:
case STNetTaskStateCancalled: {
self.stateToBlock = nil;
}
break;
default:
break;
}
});
}
@end