Consume your GraphQL API with kotlin coroutines

Martin Bonnin
Apr 23 · 3 min read

At Dailymotion, we like GraphQL…a lot. We started using it in 2016, we are active contributors to , we even have our own server implementation in Python named . When became stable we couldn’t wait to use them so we added to do so.


GraphQL APIs offer several advantages over traditional :

  • Clients only download the data they need
  • The API is introspectable and self-documented
  • Versioning is as easy as deprecating old fields and adding new ones
  • Tools like apollo-android and graphiql make a great developer experience

Coroutines offer several advantages over threads/RxJava/(AsyncTasks!):

  • Lightweight. No threads are needed to make a suspending function
  • Code is easier to read as it is written sequentially
  • Exceptions and backtraces are also easier to read since you don’t lose the original call site

Bringing GraphQL and coroutines together

Coroutines support is included in version 1.0.0. In addition to the regular apollo-android dependencies, you will also need `apollo-coroutines-support`:

Also, add your API schema and GraphQL query to your project:

A simple query

For one-shot queries, Apollo provides the ApolloQuery.toDeferred extension function. It will return a and you can call to retrieve the result:

Compared to , there’s no need for callbacks. The compiler will generate appropriate code and suspend appropriately.

Error handling

No need for error callbacks either, errors are handled with a try catch:

There are two sources of errors:

  • Transport errors will be thrown in await. These are most likely unrecoverable.
  • Graphql errors won’t be thrown by default as some implementations might be able to recover and display partial results.

In all cases, everything reads sequentially, without callbacks.

A query with cache

If you enabled cache, apollo-android will return two responses. One for the cached data and the other for the network.

For this, Apollo provides the ApolloQuery.toChannel extension function. It will return a that you can iterate on with .

Don’t forget to cancel the channel if you want to stop listening to updates.

One last thing

Apollo-android also works for any JVM project, not just Android. The samples are currently taken from Android as it’s a big use case right now but everything works on any jvm-based project. So if you’re writing your backend in kotlin, you can now use coroutines + graphql as well.

Wrapup

Consuming your GraphQL API has never been simpler! With the addition of coroutines to handle concurrency and the existing normalized cache and strong typing, GraphQL is a very strong and mature API solution today. Which is no small feat considering the language is still quite young.

If you’re interested in GraphQL, help us make and Tartiflette grow by !

Edit 2019–05–27: updated for

Dailymotion

The home for videos that matter

Martin Bonnin

Written by

Dailymotion

The home for videos that matter