react-native-nitro-sse 2.1.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NitroSse.podspec CHANGED
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
10
10
  s.license = package["license"]
11
11
  s.authors = package["author"]
12
12
 
13
- s.platforms = { :ios => min_ios_version_supported }
13
+ s.platforms = { :ios => min_ios_version_supported, :osx => "10.15" }
14
14
  s.source = { :git => "https://github.com/IAmTester35/react-native-nitro-sse.git", :tag => "#{s.version}" }
15
15
 
16
16
  s.source_files = [
package/README.md CHANGED
@@ -33,7 +33,8 @@ npm install react-native-nitro-sse react-native-nitro-modules
33
33
 
34
34
  | react-native-nitro-sse | react-native-nitro-modules |
35
35
  | :--------------------- | :------------------------- |
36
- | **2.0.0 - latest** | **0.35.2** |
36
+ | **2.2.0 - latest** | **0.35.4** |
37
+ | **2.0.0 - 2.1.1** | **0.35.2** |
37
38
  | **1.6.2** | **0.35.2** |
38
39
  | **1.4.0 - 1.6.1** | **0.35.0** |
39
40
  | **1.2.2 - 1.3.1** | **0.34.1** |
@@ -110,6 +111,7 @@ console.log(`Reconnections: ${stats.reconnectCount}`);
110
111
  | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
111
112
  | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
112
113
  | `autoParseJSON` | `boolean` | `false` | Automatically parse message data as JSON in a background native thread. Result is in `parsedData`. |
114
+ | `monitorNetwork` | `boolean` | `true` | Automatically hibernate connection on system network loss to save battery. |
113
115
  | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
114
116
 
115
117
  ---
@@ -1,2 +1,4 @@
1
1
  <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2
4
  </manifest>
@@ -23,6 +23,12 @@ import java.util.concurrent.atomic.AtomicLong
23
23
  import java.util.concurrent.atomic.AtomicInteger
24
24
  import java.util.UUID
25
25
  import kotlin.random.Random
26
+ import android.content.Context
27
+ import android.net.ConnectivityManager
28
+ import android.net.Network
29
+ import android.net.NetworkCapabilities
30
+ import android.net.NetworkRequest
31
+ import com.margelo.nitro.NitroModules
26
32
 
27
33
  /**
28
34
  * NitroSse implements a high-performance SSE client using OkHttp.
@@ -45,7 +51,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
45
51
  @Volatile private var eventSource: EventSource? = null
46
52
  @Volatile private var config: SseConfig? = null
47
53
  @Volatile private var requestId: String? = null
48
- private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
54
+ @Volatile private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
49
55
 
50
56
  private val isRunning = AtomicBoolean(false)
51
57
  private var wasRunningBeforePaused = false
@@ -56,8 +62,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
56
62
 
57
63
  private val eventBuffer = mutableListOf<SseEvent>()
58
64
  private var isFlushPending = AtomicBoolean(false)
65
+ private val flushRunnable = java.lang.Runnable { flushBufferToJs() }
59
66
 
60
67
  private var backoffCounter = 0
68
+ private val isAppInBackground = AtomicBoolean(false)
61
69
  private var currentReconnectAttempts = 0
62
70
  @Volatile private var lastProcessedId: String? = null
63
71
 
@@ -69,6 +77,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
69
77
 
70
78
  private var hasSubscribedToLifecycle = false
71
79
 
80
+ private var networkCallback: ConnectivityManager.NetworkCallback? = null
81
+ private var wasRunningBeforeNetworkLoss = false
82
+ private var lastNetworkCapabilities: NetworkCapabilities? = null
83
+
72
84
  companion object {
73
85
  private const val TAG = "NitroSse"
74
86
 
@@ -139,6 +151,108 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
139
151
  hasSubscribedToLifecycle = true
140
152
  }
141
153
  }
154
+
155
+ if (config.monitorNetwork != false) {
156
+ sseHandler?.post {
157
+ startNetworkMonitoring()
158
+ }
159
+ } else {
160
+ sseHandler?.post {
161
+ stopNetworkMonitoring()
162
+ }
163
+ }
164
+ }
165
+
166
+ private fun startNetworkMonitoring() {
167
+ if (networkCallback != null) return
168
+
169
+ val context = NitroModules.applicationContext ?: return
170
+ val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
171
+
172
+ networkCallback = object : ConnectivityManager.NetworkCallback() {
173
+ override fun onAvailable(network: Network) {
174
+ val capabilities = connectivityManager.getNetworkCapabilities(network)
175
+ handleNetworkChange(true, capabilities)
176
+ }
177
+
178
+ override fun onLost(network: Network) {
179
+ handleNetworkChange(false, null)
180
+ }
181
+
182
+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
183
+ handleNetworkChange(true, capabilities)
184
+ }
185
+ }
186
+
187
+ try {
188
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
189
+ connectivityManager.registerDefaultNetworkCallback(networkCallback!!)
190
+ } else {
191
+ val request = NetworkRequest.Builder()
192
+ .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
193
+ .build()
194
+ connectivityManager.registerNetworkCallback(request, networkCallback!!)
195
+ }
196
+ } catch (e: SecurityException) {
197
+ Log.e(TAG, "Failed to register network callback. Missing ACCESS_NETWORK_STATE permission.", e)
198
+ networkCallback = null
199
+ } catch (e: Exception) {
200
+ Log.e(TAG, "Failed to register network callback.", e)
201
+ networkCallback = null
202
+ }
203
+ }
204
+
205
+ private fun handleNetworkChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
206
+ sseHandler?.post {
207
+ Log.d(TAG, "Network change: available=$isAvailable")
208
+
209
+ if (isAvailable && capabilities != null) {
210
+ if (wasRunningBeforeNetworkLoss) {
211
+ Log.d(TAG, "Network restored. Resuming stream.")
212
+ wasRunningBeforeNetworkLoss = false
213
+ if (isAppInBackground.get() && config?.backgroundExecution != true) {
214
+ wasRunningBeforePaused = true
215
+ } else {
216
+ start()
217
+ }
218
+ } else if (isRunning.get()) {
219
+ // Check if interface changed (e.g. WiFi -> Cellular)
220
+ val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
221
+ val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
222
+
223
+ val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
224
+ val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
225
+
226
+ if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
227
+ Log.d(TAG, "Network interface changed. Restarting stream.")
228
+ restart()
229
+ }
230
+ }
231
+ lastNetworkCapabilities = capabilities
232
+ } else if (!isAvailable) {
233
+ if (isRunning.get()) {
234
+ Log.d(TAG, "Network lost. Hibernating.")
235
+ wasRunningBeforeNetworkLoss = true
236
+ isRunning.set(false)
237
+ connectionAttemptVersion.incrementAndGet()
238
+ performInternalCleanup()
239
+ }
240
+ lastNetworkCapabilities = null
241
+ }
242
+ }
243
+ }
244
+
245
+ private fun stopNetworkMonitoring() {
246
+ val callback = networkCallback ?: return
247
+ try {
248
+ val context = NitroModules.applicationContext
249
+ val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
250
+ connectivityManager?.unregisterNetworkCallback(callback)
251
+ } catch (e: Exception) {
252
+ Log.w(TAG, "Failed to unregister network callback: ${e.message}")
253
+ }
254
+ networkCallback = null
255
+ lastNetworkCapabilities = null
142
256
  }
143
257
 
144
258
  /**
@@ -146,6 +260,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
146
260
  * Automatically resumes the stream if it was hibernated.
147
261
  */
148
262
  override fun onStart(owner: LifecycleOwner) {
263
+ isAppInBackground.set(false)
149
264
  if (wasRunningBeforePaused) {
150
265
  Log.d(TAG, "App foregrounded. Resuming NitroSse stream.")
151
266
  wasRunningBeforePaused = false
@@ -158,6 +273,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
158
273
  * Hibernates the connection to save battery and resources.
159
274
  */
160
275
  override fun onStop(owner: LifecycleOwner) {
276
+ isAppInBackground.set(true)
161
277
  if (isRunning.get()) {
162
278
  if (config?.backgroundExecution == true) {
163
279
  Log.d(TAG, "App backgrounded. backgroundExecution is true, keeping NitroSse connection alive.")
@@ -165,7 +281,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
165
281
  }
166
282
  Log.d(TAG, "App backgrounded. Hibernating NitroSse connection.")
167
283
  wasRunningBeforePaused = true
168
- stop()
284
+ isRunning.set(false)
285
+ connectionAttemptVersion.incrementAndGet()
286
+ sseHandler?.post {
287
+ performInternalCleanup()
288
+ }
169
289
  }
170
290
  }
171
291
 
@@ -181,12 +301,13 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
181
301
  }
182
302
  }
183
303
 
184
- if (batchInterval <= 0 || shouldFlush) {
185
- flushBufferToJs()
186
- } else if (!isFlushPending.getAndSet(true)) {
187
- sseHandler?.postDelayed({
304
+ sseHandler?.post {
305
+ if (batchInterval <= 0 || shouldFlush) {
306
+ sseHandler?.removeCallbacks(flushRunnable)
188
307
  flushBufferToJs()
189
- }, batchInterval.toLong())
308
+ } else if (!isFlushPending.getAndSet(true)) {
309
+ sseHandler?.postDelayed(flushRunnable, batchInterval.toLong())
310
+ }
190
311
  }
191
312
  }
192
313
 
@@ -201,7 +322,16 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
201
322
  eventBuffer.clear()
202
323
  }
203
324
  isFlushPending.set(false)
204
- onEventsCallback?.invoke(eventsToEmit)
325
+
326
+ onEventsCallback?.let { callback ->
327
+ Handler(Looper.getMainLooper()).post {
328
+ try {
329
+ callback.invoke(eventsToEmit)
330
+ } catch (e: Exception) {
331
+ Log.e(TAG, "Error invoking onEventsCallback: ${e.message}")
332
+ }
333
+ }
334
+ }
205
335
  }
206
336
 
207
337
  private fun parseJsonToAnyMap(data: String): AnyMap? {
@@ -492,14 +622,18 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
492
622
  val currentConfig = synchronized(this@NitroSse) { config }
493
623
  if (currentConfig?.onBeforeRequest == null) {
494
624
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
495
- stop()
625
+ isRunning.set(false)
626
+ connectionAttemptVersion.incrementAndGet()
627
+ performInternalCleanup()
496
628
  return@post
497
629
  }
498
630
 
499
631
  val retries = consecutiveAuthErrors.incrementAndGet()
500
632
  if (retries >= maxAuthRetries) {
501
633
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
502
- stop()
634
+ isRunning.set(false)
635
+ connectionAttemptVersion.incrementAndGet()
636
+ performInternalCleanup()
503
637
  return@post
504
638
  }
505
639
 
@@ -510,7 +644,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
510
644
 
511
645
  if (statusCode == 400) {
512
646
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
513
- stop()
647
+ isRunning.set(false)
648
+ connectionAttemptVersion.incrementAndGet()
649
+ performInternalCleanup()
514
650
  return@post
515
651
  }
516
652
 
@@ -527,13 +663,17 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
527
663
 
528
664
  if (statusCode == 429) {
529
665
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
530
- stop()
666
+ isRunning.set(false)
667
+ connectionAttemptVersion.incrementAndGet()
668
+ performInternalCleanup()
531
669
  return@post
532
670
  }
533
671
 
534
672
  if (statusCode == 204) {
535
673
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null))
536
- stop()
674
+ isRunning.set(false)
675
+ connectionAttemptVersion.incrementAndGet()
676
+ performInternalCleanup()
537
677
  return@post
538
678
  }
539
679
 
@@ -584,7 +724,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
584
724
  if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
585
725
  Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
586
726
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
587
- stop()
727
+ isRunning.set(false)
728
+ connectionAttemptVersion.incrementAndGet()
729
+ performInternalCleanup()
588
730
  return
589
731
  }
590
732
 
@@ -631,21 +773,28 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
631
773
  */
632
774
  override fun stop() {
633
775
  isRunning.set(false)
776
+ wasRunningBeforeNetworkLoss = false
777
+ wasRunningBeforePaused = false
634
778
  val version = connectionAttemptVersion.incrementAndGet()
635
779
  sseHandler?.post {
636
- flushBufferToJs()
637
- backoffCounter = 0
638
- sseHandler?.removeCallbacksAndMessages(null)
639
- eventSource?.cancel()
640
- eventSource = null
641
- requestId?.let {
642
- NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
643
- requestId = null
644
- }
645
- isFlushPending.set(false)
780
+ performInternalCleanup()
646
781
  }
647
782
  }
648
783
 
784
+ private fun performInternalCleanup() {
785
+ // Runs on sseHandler thread
786
+ flushBufferToJs()
787
+ backoffCounter = 0
788
+ sseHandler?.removeCallbacksAndMessages(null)
789
+ eventSource?.cancel()
790
+ eventSource = null
791
+ requestId?.let {
792
+ NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
793
+ requestId = null
794
+ }
795
+ isFlushPending.set(false)
796
+ }
797
+
649
798
  /**
650
799
  * Clean up all resources, including background threads and lifecycle observers.
651
800
  * This is called by Nitro when the HybridObject is being garbage collected or JS reloads.
@@ -656,6 +805,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
656
805
  isRunning.set(false)
657
806
  connectionAttemptVersion.incrementAndGet()
658
807
 
808
+ stopNetworkMonitoring()
809
+
659
810
  try {
660
811
  eventSource?.cancel()
661
812
  eventSource = null
@@ -679,6 +830,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
679
830
  sseHandlerThread = null
680
831
  sseHandler = null
681
832
 
833
+ onEventsCallback = null
682
834
  super.dispose()
683
835
  }
684
836
  }
@@ -1,6 +1,10 @@
1
1
  import Foundation
2
2
  import NitroModules
3
3
  import LDSwiftEventSource
4
+ import Network
5
+ #if os(iOS)
6
+ import UIKit
7
+ #endif
4
8
 
5
9
  /**
6
10
  * NitroSse implements a high-performance SSE client for iOS using LDSwiftEventSource.
@@ -20,11 +24,14 @@ class NitroSse: HybridNitroSseSpec {
20
24
  deinit {
21
25
  if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
22
26
  self.stopInternal()
27
+ self.stopNetworkMonitoring()
23
28
  } else {
24
29
  sseQueue.sync {
25
30
  self.stopInternal()
31
+ self.stopNetworkMonitoring()
26
32
  }
27
33
  }
34
+ NotificationCenter.default.removeObserver(self)
28
35
  }
29
36
  private var eventSource: EventSource?
30
37
  private var config: SseConfig?
@@ -51,8 +58,15 @@ class NitroSse: HybridNitroSseSpec {
51
58
  return queue
52
59
  }()
53
60
  private var connectionAttemptVersion: Int = 0
61
+ #if os(iOS)
54
62
  private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
63
+ #endif
55
64
  private var wasRunningBeforeHibernation: Bool = false
65
+ private var isAppInBackground: Bool = false
66
+
67
+ private var pathMonitor: NWPathMonitor?
68
+ private var lastPathInterface: NWInterface.InterfaceType?
69
+ private var wasRunningBeforeNetworkLoss: Bool = false
56
70
 
57
71
  /**
58
72
  * Set up the NitroSse instance with configuration and an event callback.
@@ -68,24 +82,107 @@ class NitroSse: HybridNitroSseSpec {
68
82
  self.onEventsCallback = onEvent
69
83
 
70
84
  NotificationCenter.default.removeObserver(self)
85
+ #if os(iOS)
71
86
  NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
72
87
  NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
88
+ #endif
89
+
90
+ if config.monitorNetwork != false {
91
+ self.startNetworkMonitoring()
92
+ } else {
93
+ self.stopNetworkMonitoring()
94
+ }
95
+ }
96
+ }
97
+
98
+ private func stopNetworkMonitoring() {
99
+ dispatchPrecondition(condition: .onQueue(sseQueue))
100
+ pathMonitor?.cancel()
101
+ pathMonitor = nil
102
+ lastPathInterface = nil
103
+ }
104
+
105
+ private func startNetworkMonitoring() {
106
+ dispatchPrecondition(condition: .onQueue(sseQueue))
107
+ guard pathMonitor == nil else { return }
108
+
109
+ let monitor = NWPathMonitor()
110
+ monitor.pathUpdateHandler = { [weak self] path in
111
+ self?.sseQueue.async {
112
+ self?.handleNetworkChange(path: path)
113
+ }
114
+ }
115
+ self.pathMonitor = monitor
116
+ monitor.start(queue: sseQueue)
117
+ }
118
+
119
+ private func handleNetworkChange(path: NWPath) {
120
+ dispatchPrecondition(condition: .onQueue(sseQueue))
121
+ let isSatisfied = path.status == .satisfied
122
+
123
+ var interfaceType: NWInterface.InterfaceType? = nil
124
+ if path.usesInterfaceType(.wifi) {
125
+ interfaceType = .wifi
126
+ } else if path.usesInterfaceType(.cellular) {
127
+ interfaceType = .cellular
128
+ } else if path.usesInterfaceType(.wiredEthernet) {
129
+ interfaceType = .wiredEthernet
130
+ } else {
131
+ interfaceType = path.availableInterfaces.first?.type
132
+ }
133
+
134
+ print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
135
+
136
+ if isSatisfied {
137
+ if wasRunningBeforeNetworkLoss {
138
+ print("[NitroSse] Network restored. Resuming stream.")
139
+ wasRunningBeforeNetworkLoss = false
140
+ if self.isAppInBackground && self.config?.backgroundExecution != true {
141
+ self.wasRunningBeforeHibernation = true
142
+ } else if isRunning {
143
+ self.restart()
144
+ } else {
145
+ try? self.start()
146
+ }
147
+ } else if isRunning {
148
+ if let lastInterface = lastPathInterface, let currentInterface = interfaceType, lastInterface != currentInterface {
149
+ print("[NitroSse] Network interface changed (\(lastInterface) -> \(currentInterface)). Restarting stream.")
150
+ self.restart()
151
+ } else if lastPathInterface == nil {
152
+ print("[NitroSse] Network interface acquired. Restarting stream.")
153
+ self.restart()
154
+ }
155
+ }
156
+ } else {
157
+ if isRunning {
158
+ print("[NitroSse] Network lost. Hibernating.")
159
+ wasRunningBeforeNetworkLoss = true
160
+ self.hibernateConnection()
161
+ }
162
+ }
163
+
164
+ if isSatisfied {
165
+ self.lastPathInterface = interfaceType
73
166
  }
74
167
  }
75
168
 
76
169
  @objc private func handleAppDidEnterBackground() {
77
170
  sseQueue.async {
171
+ self.isAppInBackground = true
78
172
  guard self.isRunning, let config = self.config else { return }
79
173
 
80
174
  if config.backgroundExecution == true {
81
175
  print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
176
+ #if os(iOS)
82
177
  // Start a background task to tell the OS we want to keep running
178
+ self.cleanupBackgroundTask()
83
179
  self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") { [weak self] in
84
180
  self?.sseQueue.async {
85
181
  print("[NitroSse] Background task expired. Hibernating now.")
86
182
  self?.hibernateConnection()
87
183
  }
88
184
  }
185
+ #endif
89
186
  return
90
187
  }
91
188
 
@@ -115,6 +212,7 @@ class NitroSse: HybridNitroSseSpec {
115
212
 
116
213
  @objc private func handleAppWillEnterForeground() {
117
214
  sseQueue.async {
215
+ self.isAppInBackground = false
118
216
  self.cleanupBackgroundTask()
119
217
  if self.wasRunningBeforeHibernation {
120
218
  print("[NitroSse] App foregrounded. Resuming stream.")
@@ -126,10 +224,12 @@ class NitroSse: HybridNitroSseSpec {
126
224
 
127
225
  private func cleanupBackgroundTask() {
128
226
  dispatchPrecondition(condition: .onQueue(sseQueue))
227
+ #if os(iOS)
129
228
  if self.backgroundTaskIdentifier != .invalid {
130
229
  UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier)
131
230
  self.backgroundTaskIdentifier = .invalid
132
231
  }
232
+ #endif
133
233
  }
134
234
 
135
235
  private func pushEventToBuffer(_ event: SseEvent) {
@@ -207,6 +307,7 @@ class NitroSse: HybridNitroSseSpec {
207
307
  jitterFactor: config.jitterFactor,
208
308
  maxReconnectAttempts: config.maxReconnectAttempts,
209
309
  autoParseJSON: config.autoParseJSON,
310
+ monitorNetwork: config.monitorNetwork,
210
311
  onBeforeRequest: config.onBeforeRequest
211
312
  )
212
313
  print("[NitroSse] Headers updated for subsequent connections.")
@@ -237,7 +338,7 @@ class NitroSse: HybridNitroSseSpec {
237
338
 
238
339
  // Critical check: Ensure config is available before starting
239
340
  guard self.config != nil else {
240
- throw NSError(domain: "NitroSse", code: -1, userInfo: [NSLocalizedDescriptionKey: "NitroSse not configured. Call setup() first."])
341
+ throw RuntimeError("NitroSse not configured. Call setup() first.")
241
342
  }
242
343
 
243
344
  self.isRunning = true
@@ -312,6 +413,7 @@ class NitroSse: HybridNitroSseSpec {
312
413
  jitterFactor: currentConfig.jitterFactor,
313
414
  maxReconnectAttempts: currentConfig.maxReconnectAttempts,
314
415
  autoParseJSON: currentConfig.autoParseJSON,
416
+ monitorNetwork: currentConfig.monitorNetwork,
315
417
  onBeforeRequest: currentConfig.onBeforeRequest
316
418
  )
317
419
  self.performEstablishConnection(attemptVersion: attemptVersion)
@@ -399,6 +501,8 @@ class NitroSse: HybridNitroSseSpec {
399
501
  private func stopInternal() {
400
502
  dispatchPrecondition(condition: .onQueue(sseQueue))
401
503
  self.isRunning = false
504
+ self.wasRunningBeforeNetworkLoss = false
505
+ self.wasRunningBeforeHibernation = false
402
506
  self.eventSource?.stop()
403
507
  self.eventSource = nil
404
508
  if let rid = self.requestId {
@@ -85,6 +85,13 @@ export interface SseConfig {
85
85
  * @default false
86
86
  */
87
87
  autoParseJSON?: boolean;
88
+ /**
89
+ * Whether to automatically monitor network connectivity changes.
90
+ * If true, the client will proactively reconnect when switching networks (WiFi <-> Cellular)
91
+ * and pause/resume based on internet availability.
92
+ * @default true
93
+ */
94
+ monitorNetwork?: boolean;
88
95
  /**
89
96
  * Async interceptor called before every connection attempt (including auto-reconnects).
90
97
  * Use this to refresh tokens or calculate dynamic headers.
@@ -1 +1 @@
1
- {"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACzD;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,eAA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AM,CAAC;IAC3B,8DAA8D;IAC9D,cAAc,EAAE,MAAM,CAAC;IACvB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oCAAoC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,IAAI,GAAG,IAAI,CAAC;IAEvE;;;OAGG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;IAE5D;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;IAE/D,4BAA4B;IAC5B,KAAK,IAAI,IAAI,CAAC;IACd,2BAA2B;IAC3B,IAAI,IAAI,IAAI,CAAC;IACb,6CAA6C;IAC7C,OAAO,IAAI,IAAI,CAAC;IAChB,yCAAyC;IACzC,KAAK,IAAI,IAAI,CAAC;IACd,uBAAuB;IACvB,WAAW,IAAI,OAAO,CAAC;IACvB,iBAAiB;IACjB,QAAQ,IAAI,QAAQ,CAAC;IACrB,+BAA+B;IAC/B,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IACrD,yBAAyB;IACzB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;CACtC"}
@@ -68,6 +68,8 @@ namespace margelo::nitro::nitrosse {
68
68
  jni::local_ref<jni::JDouble> maxReconnectAttempts = this->getFieldValue(fieldMaxReconnectAttempts);
69
69
  static const auto fieldAutoParseJSON = clazz->getField<jni::JBoolean>("autoParseJSON");
70
70
  jni::local_ref<jni::JBoolean> autoParseJSON = this->getFieldValue(fieldAutoParseJSON);
71
+ static const auto fieldMonitorNetwork = clazz->getField<jni::JBoolean>("monitorNetwork");
72
+ jni::local_ref<jni::JBoolean> monitorNetwork = this->getFieldValue(fieldMonitorNetwork);
71
73
  static const auto fieldOnBeforeRequest = clazz->getField<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>("onBeforeRequest");
72
74
  jni::local_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject> onBeforeRequest = this->getFieldValue(fieldOnBeforeRequest);
73
75
  return SseConfig(
@@ -92,6 +94,7 @@ namespace margelo::nitro::nitrosse {
92
94
  jitterFactor != nullptr ? std::make_optional(jitterFactor->value()) : std::nullopt,
93
95
  maxReconnectAttempts != nullptr ? std::make_optional(maxReconnectAttempts->value()) : std::nullopt,
94
96
  autoParseJSON != nullptr ? std::make_optional(static_cast<bool>(autoParseJSON->value())) : std::nullopt,
97
+ monitorNetwork != nullptr ? std::make_optional(static_cast<bool>(monitorNetwork->value())) : std::nullopt,
95
98
  onBeforeRequest != nullptr ? std::make_optional([&]() -> std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()> {
96
99
  if (onBeforeRequest->isInstanceOf(JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaClassStatic())) [[likely]] {
97
100
  auto downcast = jni::static_ref_cast<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaobject>(onBeforeRequest);
@@ -110,7 +113,7 @@ namespace margelo::nitro::nitrosse {
110
113
  */
111
114
  [[maybe_unused]]
112
115
  static jni::local_ref<JSseConfig::javaobject> fromCpp(const SseConfig& value) {
113
- using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
116
+ using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
114
117
  static const auto clazz = javaClassStatic();
115
118
  static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
116
119
  return create(
@@ -135,6 +138,7 @@ namespace margelo::nitro::nitrosse {
135
138
  value.jitterFactor.has_value() ? jni::JDouble::valueOf(value.jitterFactor.value()) : nullptr,
136
139
  value.maxReconnectAttempts.has_value() ? jni::JDouble::valueOf(value.maxReconnectAttempts.value()) : nullptr,
137
140
  value.autoParseJSON.has_value() ? jni::JBoolean::valueOf(value.autoParseJSON.value()) : nullptr,
141
+ value.monitorNetwork.has_value() ? jni::JBoolean::valueOf(value.monitorNetwork.value()) : nullptr,
138
142
  value.onBeforeRequest.has_value() ? JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::fromCpp(value.onBeforeRequest.value()) : nullptr
139
143
  );
140
144
  }
@@ -61,13 +61,16 @@ data class SseConfig(
61
61
  val autoParseJSON: Boolean?,
62
62
  @DoNotStrip
63
63
  @Keep
64
+ val monitorNetwork: Boolean?,
65
+ @DoNotStrip
66
+ @Keep
64
67
  val onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?
65
68
  ) {
66
69
  /**
67
70
  * Create a new instance of SseConfig from Kotlin
68
71
  */
69
- constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
70
- this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
72
+ constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, monitorNetwork: Boolean?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
73
+ this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, monitorNetwork, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
71
74
 
72
75
  companion object {
73
76
  /**
@@ -77,8 +80,8 @@ data class SseConfig(
77
80
  @Keep
78
81
  @Suppress("unused")
79
82
  @JvmStatic
80
- private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
81
- return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest)
83
+ private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, monitorNetwork: Boolean?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
84
+ return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, monitorNetwork, onBeforeRequest)
82
85
  }
83
86
  }
84
87
  }
@@ -56,5 +56,7 @@ def add_nitrogen_files(spec)
56
56
  "SWIFT_OBJC_INTEROP_MODE" => "objcxx",
57
57
  # Enables stricter modular headers
58
58
  "DEFINES_MODULE" => "YES",
59
+ # Disable auto-generated ObjC header for Swift (Static linkage on Xcode 26.4 breaks here)
60
+ "SWIFT_INSTALL_OBJC_HEADER" => "NO",
59
61
  })
60
62
  end
@@ -18,7 +18,7 @@ public extension SseConfig {
18
18
  /**
19
19
  * Create a new instance of `SseConfig`.
20
20
  */
21
- init(url: String, method: HttpMethod?, headers: Dictionary<String, String>?, body: String?, backgroundExecution: Bool?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Bool?, onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?) {
21
+ init(url: String, method: HttpMethod?, headers: Dictionary<String, String>?, body: String?, backgroundExecution: Bool?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Bool?, monitorNetwork: Bool?, onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?) {
22
22
  self.init(std.string(url), { () -> bridge.std__optional_HttpMethod_ in
23
23
  if let __unwrappedValue = method {
24
24
  return bridge.create_std__optional_HttpMethod_(__unwrappedValue)
@@ -103,6 +103,12 @@ public extension SseConfig {
103
103
  } else {
104
104
  return .init()
105
105
  }
106
+ }(), { () -> bridge.std__optional_bool_ in
107
+ if let __unwrappedValue = monitorNetwork {
108
+ return bridge.create_std__optional_bool_(__unwrappedValue)
109
+ } else {
110
+ return .init()
111
+ }
106
112
  }(), { () -> bridge.std__optional_std__function_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_________ in
107
113
  if let __unwrappedValue = onBeforeRequest {
108
114
  return bridge.create_std__optional_std__function_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_________({ () -> bridge.Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____ in
@@ -277,6 +283,18 @@ public extension SseConfig {
277
283
  }()
278
284
  }
279
285
 
286
+ @inline(__always)
287
+ var monitorNetwork: Bool? {
288
+ return { () -> Bool? in
289
+ if bridge.has_value_std__optional_bool_(self.__monitorNetwork) {
290
+ let __unwrapped = bridge.get_std__optional_bool_(self.__monitorNetwork)
291
+ return __unwrapped
292
+ } else {
293
+ return nil
294
+ }
295
+ }()
296
+ }
297
+
280
298
  @inline(__always)
281
299
  var onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)? {
282
300
  return { () -> (() -> Promise<Promise<Dictionary<String, String>>>)? in
@@ -59,11 +59,12 @@ namespace margelo::nitro::nitrosse {
59
59
  std::optional<double> jitterFactor SWIFT_PRIVATE;
60
60
  std::optional<double> maxReconnectAttempts SWIFT_PRIVATE;
61
61
  std::optional<bool> autoParseJSON SWIFT_PRIVATE;
62
+ std::optional<bool> monitorNetwork SWIFT_PRIVATE;
62
63
  std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest SWIFT_PRIVATE;
63
64
 
64
65
  public:
65
66
  SseConfig() = default;
66
- explicit SseConfig(std::string url, std::optional<HttpMethod> method, std::optional<std::unordered_map<std::string, std::string>> headers, std::optional<std::string> body, std::optional<bool> backgroundExecution, std::optional<double> batchingIntervalMs, std::optional<double> maxBufferSize, std::optional<double> connectionTimeoutMs, std::optional<double> readTimeoutMs, std::optional<double> retryIntervalMs, std::optional<double> maxRetryIntervalMs, std::optional<double> jitterFactor, std::optional<double> maxReconnectAttempts, std::optional<bool> autoParseJSON, std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest): url(url), method(method), headers(headers), body(body), backgroundExecution(backgroundExecution), batchingIntervalMs(batchingIntervalMs), maxBufferSize(maxBufferSize), connectionTimeoutMs(connectionTimeoutMs), readTimeoutMs(readTimeoutMs), retryIntervalMs(retryIntervalMs), maxRetryIntervalMs(maxRetryIntervalMs), jitterFactor(jitterFactor), maxReconnectAttempts(maxReconnectAttempts), autoParseJSON(autoParseJSON), onBeforeRequest(onBeforeRequest) {}
67
+ explicit SseConfig(std::string url, std::optional<HttpMethod> method, std::optional<std::unordered_map<std::string, std::string>> headers, std::optional<std::string> body, std::optional<bool> backgroundExecution, std::optional<double> batchingIntervalMs, std::optional<double> maxBufferSize, std::optional<double> connectionTimeoutMs, std::optional<double> readTimeoutMs, std::optional<double> retryIntervalMs, std::optional<double> maxRetryIntervalMs, std::optional<double> jitterFactor, std::optional<double> maxReconnectAttempts, std::optional<bool> autoParseJSON, std::optional<bool> monitorNetwork, std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest): url(url), method(method), headers(headers), body(body), backgroundExecution(backgroundExecution), batchingIntervalMs(batchingIntervalMs), maxBufferSize(maxBufferSize), connectionTimeoutMs(connectionTimeoutMs), readTimeoutMs(readTimeoutMs), retryIntervalMs(retryIntervalMs), maxRetryIntervalMs(maxRetryIntervalMs), jitterFactor(jitterFactor), maxReconnectAttempts(maxReconnectAttempts), autoParseJSON(autoParseJSON), monitorNetwork(monitorNetwork), onBeforeRequest(onBeforeRequest) {}
67
68
 
68
69
  public:
69
70
  // SseConfig is not equatable because these properties are not equatable: onBeforeRequest
@@ -93,6 +94,7 @@ namespace margelo::nitro {
93
94
  JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor"))),
94
95
  JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts"))),
95
96
  JSIConverter<std::optional<bool>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON"))),
97
+ JSIConverter<std::optional<bool>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork"))),
96
98
  JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest")))
97
99
  );
98
100
  }
@@ -112,6 +114,7 @@ namespace margelo::nitro {
112
114
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.jitterFactor));
113
115
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.maxReconnectAttempts));
114
116
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON"), JSIConverter<std::optional<bool>>::toJSI(runtime, arg.autoParseJSON));
117
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork"), JSIConverter<std::optional<bool>>::toJSI(runtime, arg.monitorNetwork));
115
118
  obj.setProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest"), JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::toJSI(runtime, arg.onBeforeRequest));
116
119
  return obj;
117
120
  }
@@ -137,6 +140,7 @@ namespace margelo::nitro {
137
140
  if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor")))) return false;
138
141
  if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts")))) return false;
139
142
  if (!JSIConverter<std::optional<bool>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON")))) return false;
143
+ if (!JSIConverter<std::optional<bool>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork")))) return false;
140
144
  if (!JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest")))) return false;
141
145
  return true;
142
146
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "description": "High-performance Server-Sent Events (SSE) for React Native, powered by Nitro Modules.",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -89,12 +89,12 @@
89
89
  "eslint-plugin-prettier": "^5.5.4",
90
90
  "jest": "^29.7.0",
91
91
  "lefthook": "^2.0.3",
92
- "nitrogen": "0.35.2",
92
+ "nitrogen": "^0.35.4",
93
93
  "prettier": "^2.8.8",
94
94
  "react": "19.2.0",
95
95
  "react-native": "0.83.4",
96
96
  "react-native-builder-bob": "^0.40.17",
97
- "react-native-nitro-modules": "0.35.2",
97
+ "react-native-nitro-modules": "^0.35.4",
98
98
  "release-it": "^19.0.4",
99
99
  "turbo": "^2.5.6",
100
100
  "typescript": "^5.9.2"
@@ -87,6 +87,13 @@ export interface SseConfig {
87
87
  * @default false
88
88
  */
89
89
  autoParseJSON?: boolean;
90
+ /**
91
+ * Whether to automatically monitor network connectivity changes.
92
+ * If true, the client will proactively reconnect when switching networks (WiFi <-> Cellular)
93
+ * and pause/resume based on internet availability.
94
+ * @default true
95
+ */
96
+ monitorNetwork?: boolean;
90
97
  /**
91
98
  * Async interceptor called before every connection attempt (including auto-reconnects).
92
99
  * Use this to refresh tokens or calculate dynamic headers.