Emitting event from AppDelegate to React Native

37 views Asked by At

I want to be able to send events to React level from my AppDelegate. I created a bridge module

#import "RCTBridgeModule.h"

@implementation RCTBridgeModule {
  bool hasListeners;
}
  
static RCTBridgeModule *sharedInstance = nil;
  

RCT_EXPORT_MODULE()

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (NSArray<NSString *> *)supportedEvents {
    return @[@"StatusChangedEvent"];
}

- (void)emitEvent:(NSString *)event andData:(NSDictionary *)data {
  if (self->hasListeners) {
    [self sendEventWithName:event body:data];
  }
}

- (void)startObserving {
  self->hasListeners = YES;
}

- (void)stopObserving {
    // Implement this method if necessary
  self->hasListeners = NO;
}

- (dispatch_queue_t)methodQueue {
    return dispatch_get_main_queue();
}

@end

I registering for the events like this:

import { NativeEventEmitter, NativeModules } from 'react-native';

const { BridgeModule } = NativeModules;

const statusChangedEmitter = new NativeEventEmitter(BridgeModule);

statusChangedEmitter.addListener('StatusChangedEvent', (status) => {
  console.log('StatusChangedEvent', status);
});

At some point in my AppDelegate I am calling for:

RCTBridgeModule *statusChangedModule = [RCTBridgeModule sharedInstance];
    [statusChangedModule emitEvent:@"StatusChangedEvent"
                           andData:@{@"name": @"max"}];

However, the event is not emitted, it reaches the if-check self->hasListeners and the event is not sent. During the launch I do see that startObserving is called, however when the sharedInstance is called there's no instance of the Module and the hasListeners is set to false. Why is that? How can I set it correctly so that I will be able to emit message through the AppDelegate.

0

There are 0 answers