|
| 1 | +# RxJS interop with Angular signals |
| 2 | + |
| 3 | +The `@angular/core/rxjs-interop` package offers APIs that help you integrate RxJS and Angular signals. |
| 4 | + |
| 5 | +## Create a signal from an RxJs Observable with `toSignal` |
| 6 | + |
| 7 | +Use the `toSignal` function to create a signal which tracks the value of an Observable. It behaves similarly to the `async` pipe in templates, but is more flexible and can be used anywhere in an application. |
| 8 | + |
| 9 | +```ts |
| 10 | +import { Component } from '@angular/core'; |
| 11 | +import { AsyncPipe } from '@angular/common'; |
| 12 | +import { interval } from 'rxjs'; |
| 13 | +import { toSignal } from '@angular/core/rxjs-interop'; |
| 14 | + |
| 15 | +@Component({ |
| 16 | + template: `{{ counter() }}`, |
| 17 | +}) |
| 18 | +export class Ticker { |
| 19 | + counterObservable = interval(1000); |
| 20 | + |
| 21 | + // Get a `Signal` representing the `counterObservable`'s value. |
| 22 | + counter = toSignal(this.counterObservable, {initialValue: 0}); |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +Like the `async` pipe, `toSignal` subscribes to the Observable immediately, which may trigger side effects. The subscription created by `toSignal` automatically unsubscribes from the given Observable when the component or service which calls `toSignal` is destroyed. |
| 27 | + |
| 28 | +IMPORTANT: `toSignal` creates a subscription. You should avoid calling it repeatedly for the same Observable, and instead reuse the signal it returns. |
| 29 | + |
| 30 | +### Injection context |
| 31 | + |
| 32 | +`toSignal` by default needs to run in an [injection context](guide/di/dependency-injection-context), such as during construction of a component or service. If an injection context is not available, you can manually specify the `Injector` to use instead. |
| 33 | + |
| 34 | +### Initial values |
| 35 | + |
| 36 | +Observables may not produce a value synchronously on subscription, but signals always require a current value. There are several ways to deal with this "initial" value of `toSignal` signals. |
| 37 | + |
| 38 | +#### The `initialValue` option |
| 39 | + |
| 40 | +As in the example above, you can specify an `initialValue` option with the value the signal should return before the Observable emits for the first time. |
| 41 | + |
| 42 | +#### `undefined` initial values |
| 43 | + |
| 44 | +If you don't provide an `initialValue`, the resulting signal will return `undefined` until the Observable emits. This is similar to the `async` pipe's behavior of returning `null`. |
| 45 | + |
| 46 | +#### The `requireSync` option |
| 47 | + |
| 48 | +Some Observables are guaranteed to emit synchronously, such as `BehaviorSubject`. In those cases, you can specify the `requireSync: true` option. |
| 49 | + |
| 50 | +When `requiredSync` is `true`, `toSignal` enforces that the Observable emits synchronously on subscription. This guarantees that the signal always has a value, and no `undefined` type or initial value is required. |
| 51 | + |
| 52 | +### `manualCleanup` |
| 53 | + |
| 54 | +By default, `toSignal` automatically unsubscribes from the Observable when the component or service that creates it is destroyed. |
| 55 | + |
| 56 | +To override this behavior, you can pass the `manualCleanup` option. You can use this setting for Observables that complete themselves naturally. |
| 57 | + |
| 58 | +### Error and Completion |
| 59 | + |
| 60 | +If an Observable used in `toSignal` produces an error, that error is thrown when the signal is read. |
| 61 | + |
| 62 | +If an Observable used in `toSignal` completes, the signal continues to return the most recently emitted value before completion. |
| 63 | + |
| 64 | +## Create an RxJS Observable from a signal with `toObservable` |
| 65 | + |
| 66 | +Use the `toObservable` utility to create an `Observable` which tracks the value of a signal. The signal's value is monitored with an `effect` which emits the value to the Observable when it changes. |
| 67 | + |
| 68 | +```ts |
| 69 | +import { Component, signal } from '@angular/core'; |
| 70 | +import { toObservable } from '@angular/core/rxjs-interop'; |
| 71 | + |
| 72 | +@Component(/* ... */) |
| 73 | +export class SearchResults { |
| 74 | + query: Signal<string> = inject(QueryService).query; |
| 75 | + query$ = toObservable(this.query); |
| 76 | + |
| 77 | + results$ = this.query$.pipe( |
| 78 | + switchMap(query => this.http.get('/search?q=' + query )) |
| 79 | + ); |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +As the `query` signal changes, the `query$` Observable emits the latest query and triggers a new HTTP request. |
| 84 | + |
| 85 | +### Injection context |
| 86 | + |
| 87 | +`toObservable` by default needs to run in an [injection context](guide/di/dependency-injection-context), such as during construction of a component or service. If an injection context is not available, you can manually specify the `Injector` to use instead. |
| 88 | + |
| 89 | +### Timing of `toObservable` |
| 90 | + |
| 91 | +`toObservable` uses an effect to track the value of the signal in a `ReplaySubject`. On subscription, the first value (if available) may be emitted synchronously, and all subsequent values will be asynchronous. |
| 92 | + |
| 93 | +Unlike Observables, signals never provide a synchronous notification of changes. Even if you update a signal's value multiple times, `toObservable` will only emit the value after the signal stabilizes. |
| 94 | + |
| 95 | +```ts |
| 96 | +const obs$ = toObservable(mySignal); |
| 97 | +obs$.subscribe(value => console.log(value)); |
| 98 | + |
| 99 | +mySignal.set(1); |
| 100 | +mySignal.set(2); |
| 101 | +mySignal.set(3); |
| 102 | +``` |
| 103 | + |
| 104 | +Here, only the last value (3) will be logged. |
| 105 | + |
| 106 | +## Using `rxResource` for async data |
| 107 | + |
| 108 | +IMPORTANT: `rxResource` is [experimental](reference/releases#experimental). It's ready for you to try, but it might change before it is stable. |
| 109 | + |
| 110 | +Angular's [`resource` function](/guide/signals/resource) gives you a way to incorporate async data into your application's signal-based code. Building on top of this pattern, `rxResource` lets you define a resource where the source of your data is defined in terms of an RxJS `Observable`. Instead of accepting a `loader` function, `rxResource` accepts a `stream` function that accepts an RxJS `Observable`. |
| 111 | + |
| 112 | +```typescript |
| 113 | +import {Component, inject} from '@angular/core'; |
| 114 | +import {rxResource} from '@angular/core/rxjs-interop'; |
| 115 | + |
| 116 | +@Component(/* ... */) |
| 117 | +export class UserProfile { |
| 118 | + // This component relies on a service that exposes data through an RxJS Observable. |
| 119 | + private userData = inject(MyUserDataClient); |
| 120 | + |
| 121 | + protected userId = input<string>(); |
| 122 | + |
| 123 | + private userResource = rxResource({ |
| 124 | + params: () => this.userId(), |
| 125 | + |
| 126 | + // The `stream` property expects a factory function that returns |
| 127 | + // a data stream as an RxJS Observable. |
| 128 | + stream: ({params}) => this.userData.load(params.userId), |
| 129 | + }); |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +The `stream` property accepts a factory function for an RxJS `Observable`. This factory function is passed the resource's `params` value and returns an `Observable`. The resource calls this factory function every time the `params` computation produces a new value. See [Resource loaders](/guide/signals/resource#resource-loaders) for more details on the parameters passed to the factory function. |
| 134 | + |
| 135 | +In all other ways, `rxResource` behaves like and provides the same APIs as `resource` for specifying parameters, reading values, checking loading state, and examining errors. |
0 commit comments