fun ApolloSubscriptionCall.toFlowCacheSafely(): Flow> = callbackFlow { val clone = clone() var pendingException: ApolloException? = null var hasResponse: Boolean = false clone.execute( object : ApolloSubscriptionCall.Callback { override fun onConnected() { } override fun onResponse(response: Response) { runCatching { channel.offer(response) hasResponse = true if (pendingException != null) { channel.close(pendingException) } } } override fun onFailure(e: ApolloException) { pendingException = e if (hasResponse) { channel.close(e) } } override fun onCompleted() { channel.close() } override fun onTerminated() { channel.close() } } ) awaitClose { clone.cancel() } }