Docs
Launch GraphOS Studio
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

Using with Java


This article describes how to use in Java projects.

Use the Java codegen

generates Kotlin code by default, but you can configure it to use the Java codegen instead:

build.gradle[.kts]
apollo {
service("service") {
generateKotlinModels.set(false)
}
}

The Java runtime

The default runtime for , 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 from Java. To use it, add a dependency on this runtime instead of the default one:

build.gradle[.kts]
dependencies {
// ...
// Use apollo-runtime-java instead of apollo-runtime
implementation("com.apollographql.apollo3:apollo-runtime-java:4.0.0-beta.4")
}

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 asynchronously
apolloClient.query(new GetRandomQuery()).enqueue(response -> {
if (response.data != null) {
// No errors
System.out.println(response.data);
} else {
// Errors
if (response.exception instanceof ApolloGraphQLException) {
// GraphQL errors
System.out.println(((ApolloGraphQLException) response.exception).getErrors().get(0));
} else {
// Network error
response.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.

Previous
Using aliases
Next
Kotlin native
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company