TypeScript Subscription Operations
The third type of operation is a subscription. Subscriptions are similar to queries, but instead of returning a single result, they return a stream of results. Let's create a subscription that returns the user with the given id every second.
What's special about the subscription operation is the handler
function. It's an async generator function, which means it can yield multiple values. Instead of using the return
keyword, you have to use the yield
keyword to return a value. You can use yield
multiple times, and the client will receive a stream of results.
Let's call this operation using curl:
The result should be:
The result will be streamed to the client. If you want to unsubscribe, you can close the connection. In curl, you can do this by pressing Ctrl+C
, and the stream will end.
Streaming partial results
Another very interesting feature of subscriptions is that you can stream partial results. Let's say you have a view that requires data from multiple data sources. You can kick off multiple requests in parallel, and stream the results as they come in.
Here's an example. Let's say we're building a newsfeed for a user. Loading the user info is fast, but loading the posts is slow. We can kick off the requests in parallel, and stream the results as they come in.
The result should be:
After a second, the result will be:
Thanks to this architecture, you can easily build great user experiences that show data as soon as it's available, but without blocking the UI rendering until all data is available.
You can use subscriptions just like queries, but with the additional benefit that you can partially render the results.