React Native SDK Offline Handling

  • 3 April 2024
  • 0 replies
  • 16 views

 

 

The main focus of this community post is to highlight how Segment handles offline situations using its React Native SDK, also having a closer look at the iOS library code to see how it works.


 

Offline Handling in Segment React Native SDK

 

When the React Native SDK tries to send an event and the device is offline, the event is not lost. Instead, it is saved into a queue. The SDK keeps attempting to send these queued events whenever the device regains its network connection. This queueing mechanism ensures that no events are lost due to temporary network connectivity issues.

The offline handling mechanism is actually part of the underlying native libraries (iOS and Android).


 

Offline Handling in Native Libraries (iOS example)

 

To illustrate how offline handling works in native libraries, let's look at the iOS library (Objective-C).

The core of the offline handling logic resides in a method called flush within the SEGSegmentIntegration.m file. Here's a simplified version of the flush method flow:
 

  1. When the flush method is invoked, it first checks if a flushing operation is already in progress. If there's an ongoing operation, the method simply returns to avoid initiating another one.

  2. Next, the method checks if there are any queued messages. If the queue is empty, the method returns without initiating a flushing operation.

  3. If there are messages in the queue and no ongoing flushing operation, the method initiates an asynchronous network operation to send the queued messages to Segment's servers.

  4. If the operation fails (possibly due to being offline), the failure is logged, but the messages remain in the queue. They will be attempted again during the next flush operation.

  5. If the operation succeeds, the successfully sent messages are removed from the queue.

 

Code Block:

- (void)flush
{
@synchronized(self) {
if (self.flushing) {
return;
}

if (self.queue.count == 0) {
SEGLog(@"%@ No queued API calls to flush.", self);
return;
}

self.flushing = YES;
__block NSArray *batch = [self.queue subarrayWithRange:NSMakeRange(0, MIN(self.queue.count, 50))];
__block NSUInteger before = self.queue.count;
SEGLog(@"%@ Flushing %lu of %lu queued API calls.", self, (unsigned long)batch.count, (unsigned long)before);
//...
// further code to actually perform the flushing operation

 

The actual network reachability checking and reattempt of failed requests are handled by the standard networking APIs provided by iOS, which retry the requests when the network connection is regained.


 

Relevant Code and Repositories

Here are the resources and repositories we've used for this community post:

 


0 replies

Be the first to reply!

Reply