Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class ApolloSubscriptionClientFactory {
fun createSubscriptionApolloClient(sharedOkHttpClientBuilder: OkHttpClient.Builder): ApolloClient {
val okHttpClient = sharedOkHttpClientBuilder
.pingInterval(KEEP_ALIVE_INTERVAL, TimeUnit.SECONDS)
.build()
val subscriptionTransportFactory = WebSocketSubscriptionTransport.Factory("wss://your_subscription_host/graphql", okHttpClient)
return ApolloClient.builder()
.serverUrl("https://your_host_url/graphql")
.okHttpClient(okHttpClient)
.subscriptionConnectionParams(HeadersProvider.HEADERS)
.subscriptionTransportFactory(subscriptionTransportFactory)
.build()
}
// ...
}
class GraphQLApi(private val sharedOkHttpClientBuilder: OkHttpClient.Builder) {
// ...
fun <D : Operation.Data, V : Operation.Variables> subscribe(subscription: Subscription<D, D, V>): Flowable<Response<D>> {
// Create our dedicated apollo client
val apolloClient = ApolloSubscriptionClientFactory(sharedOkHttpClientBuilder)
.createSubscriptionApolloClient()
// Perform the actual subscription
val call = apolloClient.subscribe(subscription)
// Subscribe using Rx2Apollo
return Rx2Apollo.from<D>(call)
}
// ...
}
object HeadersProvider {
val HEADERS = mapOf(
"Authorization" to "Bearer XYZ",
"other_shared_headers" to "etc.."
)
}
class SomePresenterOrViewModelEtc(private val api: GraphQLApi) {
// ...
fun sunscribeToMessages() {
val messagesSubscription = OnNewMessagesReceivedSubscription.builder()
.groupUUID("uuid")
.build()
api.subscribe(messagesSubscription)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
// handle results, like adding the result into a list
}, {
// handle errors
}).addTo(compositeDisposable)
}
// ...
}
subscription onNewMessagesReceived($groupUUID: String!) {
groupChatSubscription(group: $groupUUID) {
... on Message {
uuid
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment