Skip to content
This repository has been archived by the owner on Apr 15, 2023. It is now read-only.

Commit

Permalink
Add invalidate to prevent multiple connections on refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanbyron committed Oct 27, 2015
1 parent 8c3e8ab commit e84996f
Showing 1 changed file with 30 additions and 23 deletions.
53 changes: 30 additions & 23 deletions RNEventSource/RNEventSource.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTUtils.h"
#import "EventSource.h"

#import "RNEventSource.h"
Expand All @@ -20,48 +21,54 @@ @implementation RNEventSource

RCT_EXPORT_MODULE();

- (void)dealloc{
- (void)invalidate
{
[self.eventSource close];
self.eventSource = nil;
}

- (void)dealloc{
[self invalidate];
}

RCT_EXPORT_METHOD(connectWithURL:(NSString *)URLString){
NSURL *serverURL = [NSURL URLWithString:URLString];

self.eventSource = [EventSource eventSourceWithURL:serverURL];

[self.eventSource onOpen: ^(Event *e) {
RCTLogInfo(@"EventSource: Connected");
RCTLogInfo(@"RNEventSource: onOpen");

[self.bridge.eventDispatcher sendDeviceEventWithName:@"EventSourceConnected"
body:@{@"event": @"connected",
// Guard against null values as NSMutableDictionary
// expects objects
@"data": e.data ? e.data : [NSNull null]}];
@"data": [NSNull null]}];
}];

[self.eventSource onError: ^(Event *e) {
RCTLogInfo(@"EventSource: Error %@: %@", e.event, e.data);
RCTLogInfo(@"RNEventSource: onError (%@)", e.error);

[self.bridge.eventDispatcher sendDeviceEventWithName:@"EventSourceError"
body:@{@"event": @"error",
// Guard against null values as NSMutableDictionary
// expects objects
@"data": e.data ? e.data : [NSNull null]}];
body:@{
@"domain": RCTNullIfNil(e.error.domain),
@"code": [NSNumber numberWithInteger:e.error.code],
@"description": e.error.userInfo[@"NSLocalizedDescription"]
}];
[self close];
}];

[self.eventSource onMessage: ^(Event *e) {
RCTLogInfo(@"%@: %@", e.event, e.data);
RCTLogInfo(@"RNEventSource: onMessage (%@: %@)", e.event, e.data);

[self.bridge.eventDispatcher sendDeviceEventWithName:@"EventSourceMessage"
body:@{@"event": e.event ? e.event : [NSNull null],
@"data": e.data ? e.data : [NSNull null]}];
body:@{@"event": RCTNullIfNil(e.event),
@"data": RCTNullIfNil(e.data)}];
}];

}

RCT_EXPORT_METHOD(close){
[self.eventSource close];
RCTLogInfo(@"EventSource: Closed");
RCTLogInfo(@"RNEventSource: Closed");
}

@end
@end

0 comments on commit e84996f

Please sign in to comment.