Using with 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 use the Java codegen 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.3")}
The Java runtime has a callbacks based API. This snippet demonstrates initializing and using an ApolloClient
in Java:
import com.apollographql.apollo3.runtime.java.ApolloClient;// (...)ApolloClient client = ApolloClient.Builder builder = new ApolloClient.Builder().serverUrl("http://localhost:4000/graphql").build();// Use enqueue to execute a query asynchronouslyapolloClient.query(new GetRandomQuery()).enqueue(response -> {if (response.data != null) {// No errorsSystem.out.println(response.data);} else {// Errorsif (response.exception instanceof ApolloGraphQLException) {// GraphQL errorsSystem.out.println(((ApolloGraphQLException) response.exception).getErrors().get(0));} else {// Network errorresponse.exception.printStackTrace();}}});
Note that as of now, the Java runtime doesn't support the Http or Normalized caches.
Cancelling requests
euqueue
returns an ApolloDisposable
that can be used to cancel the request:
ApolloDisposable disposable = apolloClient.subscription(new MyQuery()).enqueue(response -> ...)// ...disposable.dispose();
RxJava extensions
If your project uses RxJava, you can use Apollo's RxJava extensions with the Java runtime.