<!--
{
  "availability" : [

  ],
  "documentType" : "symbol",
  "framework" : "Tor",
  "identifier" : "/documentation/Tor/TorControlClient/subscribe(to:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Tor"
    ],
    "preciseIdentifier" : "s:3Tor0A13ControlClientC9subscribe2toScSyAA0aB12EventMessageVGShyAA0abF0OG_tYaKF"
  },
  "title" : "subscribe(to:)"
}
-->

# subscribe(to:)

Subscribe to Tor async events and return a stream of decoded
messages.

```
func subscribe(to events: Set<TorControlEvent>) async throws -> AsyncStream<TorControlEventMessage>
```

## Parameters

`events`

Events to subscribe to.

## Return Value

An `AsyncStream<TorControlEventMessage>` producing
decoded events until the connection closes or the consumer
cancels the owning task.

## Discussion

Issues `SETEVENTS <keywords>` (control-spec.txt §4) with the
space-joined raw values of `events`, then spawns a background
`Task` that reads lines from the socket via
[`readLineAsync()`](/documentation/Tor/ControlSocket/readLineAsync()), routes each `650`-status
line through [`parseAsyncEvent(_:)`](/documentation/Tor/ControlProtocolParser/parseAsyncEvent(_:)),
and yields the result into the returned stream.

The subscription stays active for the life of the control
connection. Call [`subscribe(to:)`](/documentation/Tor/TorControlClient/subscribe(to:)) with an empty `events`
set to unsubscribe (Tor’s convention).

> Throws: ``doc://Tor/documentation/Tor/TorError/controlProtocolError(code:message:)`` if
> Tor rejects the `SETEVENTS` command (e.g. unknown event
> keyword).

> Important: Only one subscribe loop should read from a given
> ``doc://Tor/documentation/Tor/ControlSocket`` at a time — two concurrent
> ``doc://Tor/documentation/Tor/TorControlClient/subscribe(to:)`` streams on the same client will interleave
> reads and fragment events. Use one ``doc://Tor/documentation/Tor/TorControlClient`` per
> subscriber.