Using Java
This article describes how to use Apollo Kotlin in Java projects.
Use the Java codegen
Apollo Kotlin generates Kotlin code by default, but you can configure it to generate Java code instead:
apollo {service("service") {generateKotlinModels.set(false)}}
The Java runtime
The default runtime for Apollo Kotlin, apollo-runtime
, exposes a coroutines / Flow-based API that isn't well suited to be consumed from Java.
That is why a specific runtime, apollo-runtime-java
is available to use Apollo Kotlin from Java. To use it, add a dependency on this runtime instead of the default one:
dependencies {// ...// Use apollo-runtime-java instead of apollo-runtimeimplementation("com.apollographql.apollo3:apollo-runtime-java:4.0.0-beta.7")}
Note that the Java runtime currently doesn't support the HTTP or normalized caches.
The Java runtime has a callbacks based API. This snippet demonstrates initializing an ApolloClient
and executing a query in Java:
import com.apollographql.apollo3.runtime.java.ApolloClient;// (...)// Create and configure an ApolloClientApolloClient client = ApolloClient.Builder builder = new ApolloClient.Builder().serverUrl("https://example.com/graphql").build();// Call enqueue() to execute a query asynchronouslyapolloClient.query(new MyQuery()).enqueue(response -> {if (response.data != null) {// Handle (potentially partial) dataSystem.out.println(response.data);} else {// Something wrong happenedif (response.exception != null) {// Handle non-GraphQL errors, e.g. network issuesresponse.exception.printStackTrace();} else {// Handle GraphQL errors in response.errorsSystem.out.println(response.getErrors().get(0));}}});
Cancelling requests
euqueue
returns an ApolloDisposable
that can be used to cancel the request:
ApolloDisposable disposable = apolloClient.subscription(new MySubscription()).enqueue(response -> ...)// ...disposable.dispose();
Subscriptions
Please refer to the subscriptions documentation for more information about subscriptions in general, and the available protocols.
When executing subscriptions with the Java runtime, the callback passed to enqueue()
can be called several times:
ApolloClient apolloClient = new ApolloClient.Builder().serverUrl("https://example.com/graphql")// Configure a protocol factory.wsProtocolFactory(new ApolloWsProtocol.Factory()).build();// Execute the subscriptionApolloDisposable disposable = apolloClient.subscription(new MySubscription()).enqueue(response -> {System.out.println(response.dataOrThrow());});// Observe the disposable to know when the subscription is terminateddisposable.addListener(() -> {// Will be called when an operation terminates (either successfully or due to an error)});
Interceptors
Like the Kotlin runtime, the Java runtime supports interceptors.
- HTTP interceptors (
HttpInterceptor
) can be used to add headers to requests (e.g. for authentication), log requests and responses, etc. - GraphQL interceptors (
ApolloInterceptor
) can be used to modify GraphQL requests and responses, implement retry logic, etc.
// An HTTP interceptor that adds a custom header to each requestHttpInterceptor httpInterceptor = (request, chain, callback) -> {request = request.newBuilder().addHeader("my-header", "true").build();chain.proceed(request, callback);};// A GraphQL interceptor that logs the name of each operation before executing itApolloInterceptor apolloInterceptor = new ApolloInterceptor() {@Overridepublic <D extends Operation.Data> void intercept(@NotNull ApolloRequest<D> request, @NotNull ApolloInterceptorChain chain, @NotNull ApolloCallback<D> callback) {System.out.println("Executing operation: " + request.getOperation().name());chain.proceed(request, callback);}};// Configure the interceptors when building the ApolloClientapolloClient = new ApolloClient.Builder().serverUrl(...).addHttpInterceptor(httpInterceptor).addInterceptor(apolloInterceptor).build();
If you already have implemented OkHttp interceptors, you can also use them by passing your OkHttpClient
instance to the ApolloClient.Builder
:
OkHttpClient okHttpClient = new OkHttpClient.Builder().okHttpClient(myOkHttpClient).build();
RxJava extensions
If your project uses RxJava, you can use Apollo's RxJava extensions with the Java runtime.
To do so, add the apollo-rx2-support-java
or apollo-rx3-support-java
dependency to your project:
dependencies {// ...// For RxJava 2implementation("com.apollographql.apollo3:apollo-rx2-support-java:4.0.0-beta.7")// For RxJava 3implementation("com.apollographql.apollo3:apollo-rx3-support-java:4.0.0-beta.7")}
Then use the Rx2Apollo
or Rx3Apollo
classes to execute GraphQL operations and get RxJava observables:
import com.apollographql.apollo3.rx3.java.Rx3Apollo;// (...)// QueryApolloCall<MyQuery.Data> queryCall = client.query(new MyQuery());Single<ApolloResponse<MyQuery.Data>> queryResponse = Rx3Apollo.single(queryCall);queryResponse.subscribe( /* ... */ );// MutationApolloCall<MyMutation.Data> mutationCall = client.mutation(new MyMutation("my-parameter"));Single<ApolloResponse<MyMutation.Data>> mutationResponse = Rx3Apollo.single(mutationCall);mutationResponse.subscribe( /* ... */ );// SubscriptionApolloCall<MySubscription.Data> subscriptionCall = client.subscription(new MySubscription());Flowable<ApolloResponse<MySubscription.Data>> subscriptionResponse = Rx3Apollo.flowable(subscriptionCall);subscriptionResponse.subscribe( /* ... */ );