Advertisement
moshkit

Untitled

Dec 28th, 2020
1,565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.10 KB | None | 0 0
  1. fun <T> ApolloSubscriptionCall<T>.toFlowCacheSafely(): Flow<Response<T>> = callbackFlow {
  2.     val clone = clone()
  3.     var pendingException: ApolloException? = null
  4.     var hasResponse: Boolean = false
  5.     clone.execute(
  6.         object : ApolloSubscriptionCall.Callback<T> {
  7.             override fun onConnected() {
  8.             }
  9.  
  10.             override fun onResponse(response: Response<T>) {
  11.                 runCatching {
  12.                     channel.offer(response)
  13.                     hasResponse = true
  14.                     if (pendingException != null) {
  15.                         channel.close(pendingException)
  16.                     }
  17.                 }
  18.             }
  19.  
  20.             override fun onFailure(e: ApolloException) {
  21.                 pendingException = e
  22.                 if (hasResponse) {
  23.                     channel.close(e)
  24.                 }
  25.             }
  26.  
  27.             override fun onCompleted() {
  28.                 channel.close()
  29.             }
  30.  
  31.             override fun onTerminated() {
  32.                 channel.close()
  33.             }
  34.         }
  35.     )
  36.     awaitClose { clone.cancel() }
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement