Skip to main content

Subscription

GraphQL Subscriptions allow a client to subscribe to server updates.

For example, in our schema, if you want to notify a client that a movie has been added; you can add a Subscription like this:

type Query {
movies: [Movie!]!
}

type Mutation {
addMovie(title: String!, directorName: String!): Movie!
}

type Subscription {
onMovieAdded: Movie!
}

type Movie {
title: String!
director: Director!
}

type Director {
name: String!
movies: [Movie!]
}

Now, you must register a resolver which will returner either a kotlinx.coroutines.flow.Flow either a org.reactivestreams.Publisher.

import kotlinx.coroutines.flow.*

val onMovieAdded = MutableSharedFlow<Movie>()

fun main() = arianeServer {
resolvers {
Subscription {
resolve("onMovieAdded", onMovieAdded)
}
}
}.launch()

You can now emit new events like this:

import kotlinx.coroutines.flow.*

val onMovieAdded = MutableSharedFlow<Movie>()

fun main() = arianeServer {
resolvers {
Mutation {
resolve("addMovie") {
val movie = Movie(arguments["title"], Director(arguments["director"]))
movies.add(movie)

onBookAddedPublished.emit(movie)

movie
}
}
}
}.launch()

Filters

If you need to apply filters on the subscriptions, you can apply a filter directly on the resolver.

Example:

type Subscription {
onMovieAdded(director: String!): Movie!
}
import kotlinx.coroutines.flow.*

val onMovieAdded = MutableSharedFlow<Movie>()

fun main() = arianeServer {
resolvers {
Subscription {
resolve("onMovieAdded", onMovieAdded) {
movie.director.name == argument["director"]
}
}
}
}.launch()