Inconsistent behavior of onValue stream in Flutter web and mobile environments

117 views
Skip to first unread message

wonchul cho

unread,
Mar 12, 2024, 7:07:33 PM3/12/24
to Firebase Google Group

I am currently using Firebase Realtime Database in a Flutter web and mobile application. I have encountered an issue with the onValue stream that I would like to bring to your attention.

Firstly, I am monitoring the connection status using the following code:

dart

Copy code
final connectedRef = FirebaseDatabase.instance.ref(".info/connected"); connectedRef.onValue.listen((event) { final connected = event.snapshot.value as bool? ?? false; if (connected) { debugPrint("Connected."); } else { debugPrint("Not connected."); } });

This code always indicates that the connection is established successfully. However, when using an Android phone, if the screen is turned off and then back on, such as when the device is locked and unlocked, the stream attached to onValue experiences a significant delay of up to 30 seconds before reconnecting.

Here is the relevant code snippet:

dart

Copy code
static Stream<Player?> getPlayerStream(String playerId, String gameId) { final DatabaseReference database = FirebaseDatabase.instance.ref(); return database .child('players') .orderByChild('originalUserID') .equalTo(playerId) .onValue .map((event) { Player? player; if (event.snapshot.exists) { Map<dynamic, dynamic> data = event.snapshot.value as Map<dynamic, dynamic>; data.forEach((key, value) { if (value['gameId'] == gameId) { player = Player.fromJson(Map<String, dynamic>.from(value)); } }); } return player; }); }

Despite the connection status indicating no issues, the stream does not function properly. I would appreciate your assistance in understanding the reason behind this inconsistent behavior and any potential solutions or workarounds.

Frank van Puffelen

unread,
Mar 12, 2024, 7:13:11 PM3/12/24
to Firebase Google Group
It sounds like the client/SDK detects that the connection is gone. In that stage, the client/SDK will try to reconnect periodically with an exponential back-off. So the client/SDK may not reestablish the connection right away after the operating system does, due to the nature of how it connects/disconnects.

If this is indeed what you're experiencing, the best workaround is to detect the network connection in your own code and toggle the Firebase client/SDK to goOffline()/goOnline() once you detect the connection is back.
Reply all
Reply to author
Forward
0 new messages