Skip to content
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

fix: Thread safe subscription watcher cancel #523

Merged
merged 2 commits into from
Mar 7, 2022
Merged
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
16 changes: 11 additions & 5 deletions AWSAppSyncClient/AWSAppSyncSubscriptionWatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public final class AWSAppSyncSubscriptionWatcher<Subscription: GraphQLSubscripti
private var subscriptionItem: SubscriptionItem?

private let handlerQueue: DispatchQueue
private let subscriptionsQueue: DispatchQueue
private var resultHandler: SubscriptionResultHandler<Subscription>?
private var connectedCallback: (() -> Void)?
private var statusChangeHandler: SubscriptionStatusChangeHandler?
Expand Down Expand Up @@ -57,6 +58,7 @@ public final class AWSAppSyncSubscriptionWatcher<Subscription: GraphQLSubscripti
resultHandler(result, transaction, error)
}
}
self.subscriptionsQueue = subscriptionsQueue
subscriptionsQueue.async { [weak self] in
guard let self = self else {return}
if !self.isCancelled {
Expand Down Expand Up @@ -177,22 +179,26 @@ public final class AWSAppSyncSubscriptionWatcher<Subscription: GraphQLSubscripti
/// Specifically, this means that cancelling a subscription watcher will not invoke `statusChangeHandler` or
/// `resultHandler`, although it will set the internal state of the watcher to `.disconnected`
public func cancel() {
guard !self.isCancelled else { return }

if self.cancellationSource == .none {
self.cancellationSource = .user
}
performCleanUpTasksOnCancel()
self.performCleanUpTasksOnCancel()
}

internal func performCleanUpTasksOnCancel() {
isCancelled = true
status = .disconnected
resultHandler = nil
statusChangeHandler = nil

if self.cancellationSource != .error, let item = subscriptionItem {
connection?.unsubscribe(item: item)
subscriptionsQueue.async { [weak self] in
guard let self = self else {return}
if self.cancellationSource != .error, let item = self.subscriptionItem {
self.connection?.unsubscribe(item: item)
}
self.connection = nil
}
connection = nil
}

}