forked from jgarth/MCResource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MCQueue.j
118 lines (96 loc) · 1.93 KB
/
MCQueue.j
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
var MCGlobalQueueObject = nil;
@implementation MCQueue : CPObject
{
CPArray _queuedRequests;
CPArray _processedRequests;
BOOL _isRunning;
MCQueuedRequest _currentRequest;
var _queueRunningCheckFunction;
}
// Returns global queue object
+ (MCQueue)sharedQueue
{
if(!MCGlobalQueueObject)
{
MCGlobalQueueObject = [[MCQueue alloc] init];
}
return MCGlobalQueueObject;
}
- (id)init
{
if(self = [super init])
{
_queuedRequests = [];
_processedRequests = [];
}
return self;
}
#pragma mark -
#pragma mark Queue manipulation
// Append a new request to the queue
- (void)appendRequest:(MCQueuedRequest)request
{
if(!request)
return;
// Attach it
[_queuedRequests addObject:request];
// If the queue was not stopped, process it immediately
if(_isRunning)
{
[self processQueue];
}
}
// Append new requests to the queue
- (void)appendRequests:(CPArray)requests
{
if(!requests)
return;
// Attach it
[_queuedRequests addObjectsFromArray:requests];
// If the queue was not stopped, process it immediately
if(_isRunning)
{
[self processQueue];
}
}
- (CPArray)queue
{
return _queuedRequests;
}
- (MCQueuedRequest)currentRequest
{
return _currentRequest;
}
#pragma mark -
#pragma mark Queue state control
- (void)start
{
_isRunning = YES;
[self processQueue];
}
- (void)stop
{
_isRunning = NO;
}
- (BOOL)isRunning
{
return _isRunning;
}
#pragma mark -
#pragma mark Internal methods
- (void)processQueue
{
// While the queue is full and running
while([_queuedRequests count] > 0 && _isRunning)
{
_currentRequest = [_queuedRequests objectAtIndex:0];
// And get it off the heap, archive it
// Do this now because in case of synchronous callback we could end up here again
[_queuedRequests removeObject:_currentRequest];
[_processedRequests addObject:_currentRequest];
// Fire the next queued request
CPLog.debug("Starting request: " + _currentRequest);
[_currentRequest start];
}
}
@end