forked from joltup/react-native-threads
-
Notifications
You must be signed in to change notification settings - Fork 5
/
ThreadManager.m
109 lines (90 loc) · 2.73 KB
/
ThreadManager.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
#import "ThreadManager.h"
#import <React/RCTDevSettings.h>
#include <stdlib.h>
@implementation ThreadManager {
NSMutableDictionary<NSNumber *, RCTBridge *> *_threads;
}
RCT_EXPORT_MODULE();
+ (BOOL)requiresMainQueueSetup
{
return NO;
}
- (instancetype)init
{
if (self = [super init]) {
_threads = [NSMutableDictionary new];
}
return self;
}
- (void)invalidate {
for (NSNumber *threadId in _threads) {
RCTBridge *threadBridge = _threads[threadId];
[threadBridge invalidate];
}
[_threads removeAllObjects];
_threads = nil;
[super invalidate];
}
- (NSArray<NSString *> *)supportedEvents
{
return @[@"message", @"error"];
}
RCT_EXPORT_METHOD(startThread:(nonnull NSNumber *)threadId
name:(NSString *)name)
{
NSURL *threadURL = [RCTBundleURLProvider.sharedSettings jsBundleURLForBundleRoot:name
fallbackResource:name];
NSLog(@"Starting Thread %@ (id: %@)", threadURL.absoluteString, threadId);
RCTBridge *threadBridge = [[RCTBridge alloc] initWithBundleURL:threadURL
moduleProvider:nil
launchOptions:nil];
// Ensure shaking device doesn't open additional dev menus
[[threadBridge moduleForClass:RCTDevSettings.class]
setIsShakeToShowDevMenuEnabled:NO];
ThreadSelfManager *threadSelf = [threadBridge moduleForClass:ThreadSelfManager.class];
threadSelf.threadId = threadId;
threadSelf.delegate = self;
_threads[threadId] = threadBridge;
}
RCT_EXPORT_METHOD(stopThread:(nonnull NSNumber *)threadId)
{
RCTBridge *threadBridge = _threads[threadId];
if (threadBridge == nil) {
NSLog(@"Thread is Nil. abort stopping thread with id %@", threadId);
return;
}
[threadBridge invalidate];
[_threads removeObjectForKey:threadId];
}
RCT_EXPORT_METHOD(postThreadMessage:(nonnull NSNumber *)threadId
message:(NSString *)message)
{
RCTBridge *threadBridge = _threads[threadId];
if (threadBridge == nil) {
NSLog(@"Thread is Nil. abort posting to thread with id %@", threadId);
return;
}
ThreadSelfManager *threadSelf = [threadBridge moduleForClass:ThreadSelfManager.class];
[threadSelf postMessage:message];
}
- (void)didReceiveMessage:(ThreadSelfManager *)sender
message:(NSString *)message
{
id body = @{
@"id": sender.threadId,
@"message": message,
};
[self sendEventWithName:@"message"
body:body];
}
- (void)didReceiveError:(ThreadSelfManager *)sender
message:(NSString *)message
{
id body = @{
@"id": sender.threadId,
@"message": message,
};
[self sendEventWithName:@"error"
body:body];
}
@end