Remove main thread constraint from RCTReloadCommand

Summary:
In D17880909 I migrated `[bridge reload]` to RCTReloadCommand.

One thing I didn't consider too much is the plethora of things which trigger a reload, and the `RCTAssertMainQueue()` constraint. I'd rather use locking (to protect listeners list) than requiring reloads be called from main thread.

Changelog: [iOS][Fixed] Fix potential assert firing in RCTReloadCommand

Reviewed By: rodrigos-facebook

Differential Revision: D18353156

fbshipit-source-id: d20b851fc5fe6c3518dfa3db8f1fc075cf7edee9
This commit is contained in:
Peter Argany
2019-11-08 15:30:05 -08:00
committed by Facebook Github Bot
parent 8ec7e0966c
commit 7a1d96e8aa
+16 -10
View File
@@ -11,40 +11,46 @@
#import "RCTKeyCommands.h"
#import "RCTUtils.h"
/** main queue only */
static NSHashTable<id<RCTReloadListener>> *listeners;
static NSLock *listenersLock;
NSString *const RCTTriggerReloadCommandNotification = @"RCTTriggerReloadCommandNotification";
NSString *const RCTTriggerReloadCommandReasonKey = @"reason";
void RCTRegisterReloadCommandListener(id<RCTReloadListener> listener)
{
if (!listenersLock) {
listenersLock = [NSLock new];
}
[listenersLock lock];
if (!listeners) {
listeners = [NSHashTable weakObjectsHashTable];
}
#if RCT_DEV
RCTAssertMainQueue(); // because registerKeyCommandWithInput: must be called on the main thread
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
listeners = [NSHashTable weakObjectsHashTable];
[[RCTKeyCommands sharedInstance] registerKeyCommandWithInput:@"r"
modifierFlags:UIKeyModifierCommand
action:
^(__unused UIKeyCommand *command) {
RCTTriggerReloadCommandListeners(@"Command + R");
}];
RCTTriggerReloadCommandListeners(@"Command + R");
}];
});
#endif
[listeners addObject:listener];
[listenersLock unlock];
}
void RCTTriggerReloadCommandListeners(NSString *reason)
{
RCTAssertMainQueue();
[listenersLock lock];
[[NSNotificationCenter defaultCenter] postNotificationName:RCTTriggerReloadCommandNotification
object:nil
userInfo:@{RCTTriggerReloadCommandReasonKey: RCTNullIfNil(reason)} ];
// Copy to protect against mutation-during-enumeration.
// If listeners hasn't been initialized yet we get nil, which works just fine.
NSArray<id<RCTReloadListener>> *copiedListeners = [listeners allObjects];
for (id<RCTReloadListener> l in copiedListeners) {
for (id<RCTReloadListener> l in [listeners allObjects]) {
[l didReceiveReloadCommand];
}
[listenersLock unlock];
}