在 Android 上使用带有 Kotlin 和流的 Apollo 订阅 GraphQL 时处理网络错误

Handle network error when using GraphQL subscription with Apollo on Android with Kotlin and flows

我在 Android 上使用 Apollo GraphQL。我正在使用 Apollo ver 3。 我有订阅,我可以成功订阅并获取更新。 问题是,如果我在应用程序上打开 fligth 模式会崩溃,但出现异常:

    java.lang.IllegalStateException: WeSocket queue full
        at com.apollographql.apollo3.network.ws.DefaultWebSocketEngine$open.send(OkHttpWebSocketEngine.kt:90)
        at com.apollographql.apollo3.network.ws.WsProtocol.sendMessageMapBinary(WsProtocol.kt:92)
        at com.apollographql.apollo3.network.ws.SubscriptionWsProtocol.stopOperation(SubscriptionWsProtocol.kt:69)
        at com.apollographql.apollo3.network.ws.WebSocketNetworkTransport.invokeSuspend(WebSocketNetworkTransport.kt:144)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:920)

我尝试在返回的流程上使用 catch,但它不起作用。 这就是我所做的:

apolloClient.subscribe(ProfileSubscription()).execute().catch {  }

定义订阅的.grapql文件是:

subscription Profile {
    syncStatus {
        offline
    }
}

然后我通过调用创建了 Apollo 客户端:

ApolloClient.Builder()
        .networkTransport(
            WebSocketNetworkTransport(
                serverUrl = baseUrl
            )
        ).build()

基础url使用ws作为协议:

ws://ec2-xx-xxx-xxx-xx.eu-west-2.compute.amazonaws.com:4000/graphql

如何优雅地处理异常?

我刚刚在开始流程时处理了异常:

viewModelScope.launch(CoroutineExceptionHandler{ _, _ -> }) {
    profilesUpdatesUseCase.subscribe()
}

方法 profilesUpdatesUseCase.subscribe() 是调用的方法:

apolloClient.subscribe(ProfileSubscription()).execute()

当然,ViewModel 最终需要在可能的情况下重新启动流程。