Subscription
In GraphQL, Subscription allows the server to push data to the client.
Basic Usage
In GQLoom
, we use the subscription
function to define a subscription:.
In the code above, we define a countdown
subscription that accepts a seconds
parameter.
We passed in an asynchronous generator in the subscription function, which will push a number every second until the number is 0.
Using publish/subscribe
We can also use the publish/subscribe feature provided by GraphQL Yoga to push messages more easily:
In the code above, we defined a hello
query and a listenGreeting
subscription.
When the hello
query is called, it publishes a greeting
event, and the listenGreeting
subscription subscribes to this event and pushes a message when it occurs.
You can learn about the detailed usage of the Publish/Subscribe feature at GraphQL Yoga Documentation.
Using Subscriptions in Distributed Systems
The subscription feature can work easily in a monolithic application. However, in a distributed system, the subscription feature can get complicated. You may consider using the event-driven federated subscription feature from WunderGraph Cosmo to handle subscriptions in a distributed system.