Bug: Stream disconnects on App Backgrounding
Closed this issue · 2 comments
Issue:
Streams intermittently stop receiving messages after the app is backgrounded and re-foregrounded.
Reproduce:
- Initialize a stream
- Background or the app.
- Foreground the app.
- No incoming messages received.
Expected:
Stream maintains connection or reconnects after foregrounding.
Actual:
Stream 'dies' silently without errors.
It seems suspicious that this is only happening on backgrounding and then reforegrounding the app. Were you able to reproduce this @fabriguespe? I think until we can move the swift SDK over to the new subscribe2
protocol function my advice would be to detect when network or background events happen and kill the stream and then restart the stream. Long term it would be good to do what we did here in Android xmtp/xmtp-android#131 but this is a much heavier lift as it requires changes to libxmtp
.
You can kind of see how we do setting up a task and canceling it here https://github.com/xmtp/xmtp-react-native/blob/main/ios/XMTPModule.swift#L638-L655 but the cancel would also happen on background and network disconnection etc..
After running some tests, the stream
fails silently after 4-10 minutes of the app being in the background.
Here is a proposed solution that involves listening for specific app state notifications and managing the stream accordingly, preventing it from 'dying' silently without errors.
// Rest of the code ...
func startStream() {
streamTask = Task {
do {
for try await message in conversation.streamMessages() {
let content: String = try message.content()
print("Received message: \(content)")
await MainActor.run {
messages.append(message)
}
}
} catch {
print("Error in message stream: \(error)")
}
}
}
// Rest of the code ...
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { in
streamTask?.cancel()
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { in
Task{
await loadMessages()
startStreamTask()
}
}
We cancel the streamTask
when the app moves to the background (UIApplication.willResignActiveNotification
), and start a new task that loads the messages and resumes the stream when the app moves to the foreground (UIApplication.willEnterForegroundNotification
).