Skip to content

fix: Concurrent Modification Error in RealtimeMixin Causing Crashes. … #205

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions lib/src/realtime_mixin.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'exception.dart';
import 'realtime_subscription.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'client.dart';
import 'exception.dart';
import 'realtime_message.dart';
import 'realtime_response.dart';
import 'realtime_response_connected.dart';
import 'realtime_subscription.dart';

typedef WebSocketFactory = Future<WebSocketChannel> Function(Uri uri);
typedef GetFallbackCookie = String? Function();
Expand Down Expand Up @@ -87,10 +89,14 @@ mixin RealtimeMixin {
break;
}
}, onDone: () {
final subscriptions = List.from(_subscriptions.values);
for (var subscription in subscriptions) {
subscription.close();
if (!_notifyDone || _creatingSocket) return;
// create a copy of the keys to avoid concurrent modification
var subscriptionKeys = _subscriptions.keys.toList();
for (var key in subscriptionKeys) {
// close the subscription
_subscriptions[key]?.close();
}

_channels.clear();
_closeConnection();
}, onError: (err, stack) {
Expand Down Expand Up @@ -157,13 +163,23 @@ mixin RealtimeMixin {
}

void _cleanup(List<String> channels) {
// create a list of channels to remove from the list of channels
List<String> channelsToRemove = [];

for (var channel in channels) {
// check if the channel is still in use
bool found = _subscriptions.values
.any((subscription) => subscription.channels.contains(channel));

if (!found) {
_channels.remove(channel);
// if not, add it to the list of channels to remove
channelsToRemove.add(channel);
}
}

for (var channel in channelsToRemove) {
_channels.remove(channel);
}
}

void handleError(RealtimeResponse response) {
Expand Down