> For the complete documentation index, see [llms.txt](https://www.learnrxjs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.learnrxjs.io/learn-rxjs/operators/utility/finalize.md).

# finalize / finally

#### signature: `finalize(callback: () => void)`

## Call a function when observable completes or errors

### Examples

**Example 1: Execute callback function when the observable completes**

( [StackBlitz](https://stackblitz.com/edit/typescript-ohddud) )

```js
import { interval } from 'rxjs';
import { take, finalize } from 'rxjs/operators';

//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const example = source.pipe(
  take(5), //take only the first 5 values
  finalize(() => console.log('Sequence complete')) // Execute when the observable completes
)
const subscribe = example.subscribe(val => console.log(val));
```

### Related Recipes

* [Battleship Game](/learn-rxjs/recipes/battleship-game.md)
* [Car Racing Game](/learn-rxjs/recipes/car-racing-game.md)
* [Click Ninja Game](/learn-rxjs/recipes/click-ninja-game.md)
* [HTTP Polling](/learn-rxjs/recipes/http-polling.md)
* [Mine Sweeper Game](/learn-rxjs/recipes/mine-sweeper-game.md)
* [Swipe To Refresh](/learn-rxjs/recipes/swipe-to-refresh.md)
* [Tetris Game](/learn-rxjs/recipes/tetris-game.md)

### Additional Resources

* [finalize](https://rxjs.dev/api/operators/finalize) 📰 - Official docs

***

> 📁 Source Code: <https://github.com/ReactiveX/rxjs/blob/master/packages/rxjs/src/internal/operators/finalize.ts>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.learnrxjs.io/learn-rxjs/operators/utility/finalize.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
