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

Coroutines: make sure we do not crash when calling offer #2007

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
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import kotlinx.coroutines.flow.*

private class ChannelCallback<T>(val channel: Channel<Response<T>>) : ApolloCall.Callback<T>() {

@ExperimentalCoroutinesApi
override fun onResponse(response: Response<T>) {
if (!channel.isClosedForSend) {
runCatching {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sav007 I feel the runCatching approach is safer since there could potentially be a race condition where the channel is closed just after the if before. Let me know if isClosedForSend was used to catch other cases.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid having to wrap the offer in a runCatching, you could create an extension on a Channel.

fun <E> SendChannel<E>.safeOffer(value: E) = runCatching {
        offer(value)
}

Copy link
Contributor Author

@martinbonnin martinbonnin Feb 21, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@msya, for 2 instances only, I'd rather not pollute the SendChannel namespace with an extension function.

channel.offer(response)
}
}
Expand Down Expand Up @@ -196,7 +195,9 @@ fun <T> ApolloSubscriptionCall<T>.toChannel(capacity: Int = Channel.UNLIMITED):
}

override fun onResponse(response: Response<T>) {
channel.offer(response)
runCatching {
channel.offer(response)
}
}

override fun onFailure(e: ApolloException) {
Expand Down