Skip to content

Commit

Permalink
Fix race condition in websocket unsubscribe/resubscribe (#2855)
Browse files Browse the repository at this point in the history
- If the app tries to start a new websocket subscription before the last one was properly unsubscribed, the app will return a flow that is null and crash. To prevent this, change the unsubscribe logic to immediately remove the subscription ID - the confirmation isn't used. This will allow the app to start a new subscription and create a new flow even if the previous unsubscribe hasn't yet fully finished (which is OK).
  • Loading branch information
jpelgrom committed Sep 5, 2022
1 parent b2ff51f commit 45cdaeb
Showing 1 changed file with 5 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -235,20 +235,20 @@ class WebSocketRepositoryImpl @Inject constructor(
eventSubscriptionFlow[subscribeMessage] = callbackFlow<T> {
eventSubscriptionProducerScope[subscribeMessage] = this as ProducerScope<Any>
awaitClose {
if (eventSubscriptionId[subscribeMessage] != null) {
eventSubscriptionProducerScope.remove(subscribeMessage)
eventSubscriptionFlow.remove(subscribeMessage)
eventSubscriptionId[subscribeMessage]?.let {
eventSubscriptionId.remove(subscribeMessage)
Log.d(TAG, "Unsubscribing from $type with data $data")
ioScope.launch {
sendMessage(
mapOf(
"type" to "unsubscribe_events",
"subscription" to eventSubscriptionId[subscribeMessage]!!
"subscription" to it
)
)
eventSubscriptionId.remove(subscribeMessage)
}
}
eventSubscriptionProducerScope.remove(subscribeMessage)
eventSubscriptionFlow.remove(subscribeMessage)
}
}.shareIn(ioScope, SharingStarted.WhileSubscribed())
}
Expand Down

0 comments on commit 45cdaeb

Please sign in to comment.