RNNotificationsBridgeQueue.m 2.36 KB
Newer Older
1 2 3 4
#import "RNNotificationsBridgeQueue.h"

@implementation RNNotificationsBridgeQueue

5
NSMutableArray<NSDictionary *>* actionsQueue;
6
NSMutableArray<NSDictionary *>* notificationsQueue;
7 8
NSMutableDictionary* actionCompletionHandlers;

9 10 11 12 13 14 15 16 17
+ (nonnull instancetype)sharedInstance {
    static RNNotificationsBridgeQueue* sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [self new];
    });
    
    return sharedInstance;
}
18 19 20 21

- (instancetype)init
{
    actionsQueue = [NSMutableArray new];
22
    notificationsQueue = [NSMutableArray new];
23 24 25 26 27 28 29 30
    actionCompletionHandlers = [NSMutableDictionary new];
    self.jsIsReady = NO;

    return self;
}

- (void)postNotification:(NSDictionary *)notification
{
31 32
    if (!notificationsQueue) return;
    [notificationsQueue insertObject:notification atIndex:0];
33 34 35 36
}

- (NSDictionary *)dequeueSingleNotification
{
37
    if (!notificationsQueue || notificationsQueue.count == 0) return nil;
38

39 40
    NSDictionary* notification = [notificationsQueue lastObject];
    [notificationsQueue removeLastObject];
41 42 43 44 45 46 47 48 49 50 51 52

    return notification;
}

- (void)consumeNotificationsQueue:(void (^)(NSDictionary *))block
{
    NSDictionary* notification;

    while ((notification = [self dequeueSingleNotification]) != nil) {
        block(notification);
    }

53
    notificationsQueue = nil;
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
}

- (void)postAction:(NSDictionary *)action withCompletionKey:(NSString *)completionKey andCompletionHandler:(void (^)())completionHandler
{
    // store completion handler
    actionCompletionHandlers[completionKey] = completionHandler;

    if (!actionsQueue) return;
    [actionsQueue insertObject:action atIndex:0];
}

- (NSDictionary *)dequeueSingleAction
{
    if (!actionsQueue || actionsQueue.count == 0) return nil;

    NSDictionary* action = [actionsQueue lastObject];
    [actionsQueue removeLastObject];

    return action;
}

- (void)consumeActionsQueue:(void (^)(NSDictionary *))block
{
    NSDictionary* lastActionInfo;

    while ((lastActionInfo = [self dequeueSingleAction]) != nil) {
        block(lastActionInfo);
    }

    actionsQueue = nil;
}

- (void)completeAction:(NSString *)completionKey
{
    void (^completionHandler)() = (void (^)())[actionCompletionHandlers valueForKey:completionKey];
    if (completionHandler) {
        completionHandler();
        [actionCompletionHandlers removeObjectForKey:completionKey];
    }
}

95
@end