---
agentTools:
  projectIndex: https://operations.readme.io/llms.txt
---

# Observers

Observers watch Operations

Observers are attached to a single `Operation`. They receive callbacks when operation events occur. There are currently four events

[block:parameters]
{
  "data": {
    "0-0": "`OperationDidStartObserver`",
    "0-1": "Triggered directly before the operation's `execute` method is invoked.",
    "1-0": "`OperationDidCancelObserver`",
    "1-1": "Triggered if and when the operation is cancelled.",
    "2-0": "`OperationDidProduceOperationObserver`",
    "2-1": "Triggered if and when the operation produces another operation.",
    "3-0": "`OperationDidFinishObserver`",
    "3-1": "Triggered directly before the operation moves to the finished state.",
    "h-0": "Protocol",
    "h-1": "Event"
  },
  "cols": 2,
  "rows": 4
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Adding an observer"
}
[/block]

Add an observer before the operation becomes ready. If possible setup observers before adding the operation to a queue.

[block:code]
{
  "codes": [
    {
      "code": "operation.addObserver(StartedObserver { op in \n    print(\"Lets go!\")\n})",
      "language": "swift"
    }
  ]
}
[/block]

`StartedObserver`, `CancelledObserver`, `ProducedObserver` and `FinishedObserver` are all initialized with a block which is executed when the observer is trigger for its event. In the example above, the block would be executed just before `operation` has `execute` called.

If it is necessary to perform side effects when an operation starts *and* finishes, add a `StartedObserver` and a `FinishedObserver` there is no restriction on the number of observers.

The framework also includes `BackgroundObserver`, `TimeoutObserver`, and `NetworkObserver`.