-
Notifications
You must be signed in to change notification settings - Fork 81
/
MTSubscriber.m
152 lines (122 loc) · 2.76 KB
/
MTSubscriber.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#import "MTSubscriber.h"
#import <libkern/OSAtomic.h>
@interface MTSubscriberBlocks : NSObject {
@public
void (^_next)(id);
void (^_error)(id);
void (^_completed)();
}
@end
@implementation MTSubscriberBlocks
- (instancetype)initWithNext:(void (^)(id))next error:(void (^)(id))error completed:(void (^)())completed {
self = [super init];
if (self != nil) {
_next = [next copy];
_error = [error copy];
_completed = [completed copy];
}
return self;
}
@end
@interface MTSubscriber ()
{
@protected
OSSpinLock _lock;
bool _terminated;
id<MTDisposable> _disposable;
MTSubscriberBlocks *_blocks;
}
@end
@implementation MTSubscriber
- (instancetype)initWithNext:(void (^)(id))next error:(void (^)(id))error completed:(void (^)())completed
{
self = [super init];
if (self != nil)
{
_blocks = [[MTSubscriberBlocks alloc] initWithNext:next error:error completed:completed];
}
return self;
}
- (void)_assignDisposable:(id<MTDisposable>)disposable
{
bool dispose = false;
OSSpinLockLock(&_lock);
if (_terminated) {
dispose = true;
} else {
_disposable = disposable;
}
OSSpinLockUnlock(&_lock);
if (dispose) {
[disposable dispose];
}
}
- (void)_markTerminatedWithoutDisposal
{
OSSpinLockLock(&_lock);
MTSubscriberBlocks *blocks = nil;
if (!_terminated)
{
blocks = _blocks;
_blocks = nil;
_terminated = true;
}
OSSpinLockUnlock(&_lock);
if (blocks) {
blocks = nil;
}
}
- (void)putNext:(id)next
{
MTSubscriberBlocks *blocks = nil;
OSSpinLockLock(&_lock);
if (!_terminated) {
blocks = _blocks;
}
OSSpinLockUnlock(&_lock);
if (blocks && blocks->_next) {
blocks->_next(next);
}
}
- (void)putError:(id)error
{
bool shouldDispose = false;
MTSubscriberBlocks *blocks = nil;
OSSpinLockLock(&_lock);
if (!_terminated)
{
blocks = _blocks;
_blocks = nil;
shouldDispose = true;
_terminated = true;
}
OSSpinLockUnlock(&_lock);
if (blocks && blocks->_error) {
blocks->_error(error);
}
if (shouldDispose)
[self->_disposable dispose];
}
- (void)putCompletion
{
bool shouldDispose = false;
MTSubscriberBlocks *blocks = nil;
OSSpinLockLock(&_lock);
if (!_terminated)
{
blocks = _blocks;
_blocks = nil;
shouldDispose = true;
_terminated = true;
}
OSSpinLockUnlock(&_lock);
if (blocks && blocks->_completed)
blocks->_completed();
if (shouldDispose)
[self->_disposable dispose];
}
- (void)dispose
{
[self->_disposable dispose];
}
@end