Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added subscription unsubscribing info #3654

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions docs/general/subscriptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,55 @@ schema = strawberry.Schema(query=Query, subscription=Subscription)

[pep-525]: https://www.python.org/dev/peps/pep-0525/

## Unsubscribing subscriptions

In GraphQL, it is possible to unsubscribe from a subscription. Strawberry
supports this behaviour, and is done using a `try...except` block.

In Apollo-client, closing a subscription can be achieved like the following:

```javascript
const client = useApolloClient();
const subscriber = client.subscribe({query: ...}).subscribe({...})
// ...
// done with subscription. now unsubscribe
subscriber.unsubscribe();
```

Strawberry can easily capture when a subscriber unsubscribes using an
`asyncio.CancelledError` exception.

```python
import asyncio
from typing import AsyncGenerator
from uuid import uuid4

import strawberry

# track active subscribers
event_messages = {}


@strawberry.type
class Subscription:
@strawberry.subscription
async def message(self) -> AsyncGenerator[int, None]:
try:
subscription_id = uuid4()

event_messages[subscription_id] = []

while True:
if len(event_messages[subscription_id]) > 0:
yield event_messages[subscription_id]
event_messages[subscription_id].clear()

await asyncio.sleep(1)
except asyncio.CancelledError:
# stop listening to events
del event_messages[subscription_id]
```

## GraphQL over WebSocket protocols

Strawberry support both the legacy
Expand Down
Loading