# defer

#### signature: `defer(observableFactory: function(): SubscribableOrPromise): Observable`

## Create an observable with given subscription function.

***

💡 [`defer`](https://github.com/ReactiveX/rxjs/blob/ecc73d2a1564d0d3edffba90eec76510e509236c/src/internal/observable/iif.ts#L94-L100) is used as part of the [`iif`](https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif) operator!

***

### Examples

**Example 1: Defer to get current date/time at the time of subscription**

( [StackBlitz](https://stackblitz.com/edit/rxjs-defer-example?file=index.ts\&devtoolsheight=100) )

```js
// RxJS v6+
import { defer, of, timer, merge } from 'rxjs';
import { switchMap } from 'rxjs/operators';

const s1 = of(new Date()); //will capture current date time
const s2 = defer(() => of(new Date())); //will capture date time at the moment of subscription

console.log(new Date());

timer(2000)
  .pipe(switchMap(_ => merge(s1, s2)))
  .subscribe(console.log);

/*
OUTPUT => 
2019-02-10T12:38:30.000Z (currrent date/time from first console log)
2019-02-10T12:38:30.000Z (date/time in s1 console log, captured date/time at the moment of observable creation)
2019-02-10T12:38:32.000Z (date/time in s2 console log, captured date/time at the moment of subscription)
*/

/*//NOTE: 'traditional' js equivalent of timer code above is:
setTimeout(() => {
  s1.subscribe(console.log);
  s2.subscribe(console.log);
}, 2000);
*/
```

### Related Recipes

* [Save Indicator](https://www.learnrxjs.io/learn-rxjs/recipes/save-indicator)

### Additional Resources

* [defer](https://rxjs.dev/api/index/function/defer) 📰 - Official docs

***

> 📁 Source Code: <https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/defer.ts>


---

# Agent Instructions: 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/creation/defer.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.
