0
# Filtering Operators
1
2
Operators for selecting specific values from observable streams based on various criteria including predicates, time windows, and positional filters.
3
4
## Capabilities
5
6
### filter
7
8
Filter values based on a predicate function.
9
10
```typescript { .api }
11
/**
12
* Filter values based on a predicate function
13
* @param predicate - Function that returns true for values to keep
14
* @returns Operator function filtering the source observable
15
*/
16
function filter<T>(predicate: (value: T, index: number) => boolean): OperatorFunction<T, T>;
17
function filter<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { of, filter } from "rxjs";
24
25
// Filter even numbers
26
of(1, 2, 3, 4, 5, 6).pipe(
27
filter(x => x % 2 === 0)
28
).subscribe(x => console.log(x)); // 2, 4, 6
29
30
// Filter objects by property
31
of(
32
{ name: 'Alice', age: 25 },
33
{ name: 'Bob', age: 17 },
34
{ name: 'Charlie', age: 30 }
35
).pipe(
36
filter(person => person.age >= 18)
37
).subscribe(person => console.log(person.name)); // Alice, Charlie
38
```
39
40
### take
41
42
Take only the first n values.
43
44
```typescript { .api }
45
/**
46
* Take only the first count values from the source
47
* @param count - Number of values to take
48
* @returns Operator function taking first count values
49
*/
50
function take<T>(count: number): OperatorFunction<T, T>;
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { interval, take } from "rxjs";
57
58
// Take first 5 values from interval
59
interval(1000).pipe(
60
take(5)
61
).subscribe(x => console.log(x)); // 0, 1, 2, 3, 4 (then completes)
62
```
63
64
### skip
65
66
Skip the first n values.
67
68
```typescript { .api }
69
/**
70
* Skip the first count values from the source
71
* @param count - Number of values to skip
72
* @returns Operator function skipping first count values
73
*/
74
function skip<T>(count: number): OperatorFunction<T, T>;
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
import { of, skip } from "rxjs";
81
82
// Skip first 2 values
83
of(1, 2, 3, 4, 5).pipe(
84
skip(2)
85
).subscribe(x => console.log(x)); // 3, 4, 5
86
```
87
88
### first
89
90
Emit only the first value (or first matching a condition).
91
92
```typescript { .api }
93
/**
94
* Emit only the first value or first value matching predicate
95
* @param predicate - Optional predicate function
96
* @param defaultValue - Default value if no match found
97
* @returns Operator function emitting first matching value
98
*/
99
function first<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, T>;
100
function first<T, D>(predicate: (value: T, index: number) => boolean, defaultValue: D): OperatorFunction<T, T | D>;
101
function first<T, D>(predicate: null | undefined, defaultValue: D): OperatorFunction<T, T | D>;
102
```
103
104
**Usage Examples:**
105
106
```typescript
107
import { of, first } from "rxjs";
108
109
// First value
110
of(1, 2, 3).pipe(first()).subscribe(x => console.log(x)); // 1
111
112
// First even number
113
of(1, 3, 4, 5, 6).pipe(
114
first(x => x % 2 === 0)
115
).subscribe(x => console.log(x)); // 4
116
117
// With default value
118
of(1, 3, 5).pipe(
119
first(x => x % 2 === 0, -1)
120
).subscribe(x => console.log(x)); // -1 (no even numbers found)
121
```
122
123
### last
124
125
Emit only the last value (or last matching a condition).
126
127
```typescript { .api }
128
/**
129
* Emit only the last value or last value matching predicate
130
* @param predicate - Optional predicate function
131
* @param defaultValue - Default value if no match found
132
* @returns Operator function emitting last matching value
133
*/
134
function last<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, T>;
135
function last<T, D>(predicate: (value: T, index: number) => boolean, defaultValue: D): OperatorFunction<T, T | D>;
136
function last<T, D>(predicate: null | undefined, defaultValue: D): OperatorFunction<T, T | D>;
137
```
138
139
**Usage Examples:**
140
141
```typescript
142
import { of, last } from "rxjs";
143
144
// Last value
145
of(1, 2, 3).pipe(last()).subscribe(x => console.log(x)); // 3
146
147
// Last even number
148
of(1, 2, 4, 5, 6, 7).pipe(
149
last(x => x % 2 === 0)
150
).subscribe(x => console.log(x)); // 6
151
```
152
153
### distinct
154
155
Emit only distinct values.
156
157
```typescript { .api }
158
/**
159
* Emit only values that are distinct from previous values
160
* @param keySelector - Optional function to select comparison key
161
* @param flushes - Optional observable that flushes the distinct key collection
162
* @returns Operator function emitting distinct values
163
*/
164
function distinct<T>(keySelector?: (value: T) => any): OperatorFunction<T, T>;
165
function distinct<T>(keySelector: (value: T) => any, flushes: Observable<any>): OperatorFunction<T, T>;
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
import { of, distinct } from "rxjs";
172
173
// Distinct numbers
174
of(1, 1, 2, 2, 3, 1).pipe(
175
distinct()
176
).subscribe(x => console.log(x)); // 1, 2, 3
177
178
// Distinct by property
179
of(
180
{ id: 1, name: 'Alice' },
181
{ id: 2, name: 'Bob' },
182
{ id: 1, name: 'Alice' },
183
{ id: 3, name: 'Charlie' }
184
).pipe(
185
distinct(person => person.id)
186
).subscribe(person => console.log(person.name)); // Alice, Bob, Charlie
187
```
188
189
### distinctUntilChanged
190
191
Emit only when current value differs from previous value.
192
193
```typescript { .api }
194
/**
195
* Emit only when current value differs from the previous value
196
* @param compare - Optional comparison function
197
* @param keySelector - Optional key selector function
198
* @returns Operator function emitting when value changes
199
*/
200
function distinctUntilChanged<T>(compare?: (previous: T, current: T) => boolean): OperatorFunction<T, T>;
201
function distinctUntilChanged<T, K>(compare: (previous: K, current: K) => boolean, keySelector: (value: T) => K): OperatorFunction<T, T>;
202
```
203
204
**Usage Examples:**
205
206
```typescript
207
import { of, distinctUntilChanged } from "rxjs";
208
209
// Consecutive duplicates removed
210
of(1, 1, 2, 2, 2, 1, 3).pipe(
211
distinctUntilChanged()
212
).subscribe(x => console.log(x)); // 1, 2, 1, 3
213
214
// Custom comparison
215
of(
216
{ id: 1, name: 'Alice' },
217
{ id: 1, name: 'Alice Updated' },
218
{ id: 2, name: 'Bob' }
219
).pipe(
220
distinctUntilChanged((prev, curr) => prev.id === curr.id)
221
).subscribe(person => console.log(person)); // First Alice, Bob only
222
```
223
224
### debounceTime
225
226
Emit values only after a silence period.
227
228
```typescript { .api }
229
/**
230
* Emit values only after specified silence duration
231
* @param dueTime - Silence duration in milliseconds
232
* @param scheduler - Optional scheduler
233
* @returns Operator function debouncing by time
234
*/
235
function debounceTime<T>(dueTime: number, scheduler?: SchedulerLike): OperatorFunction<T, T>;
236
```
237
238
**Usage Examples:**
239
240
```typescript
241
import { fromEvent, debounceTime, map } from "rxjs";
242
243
// Debounce user input
244
const searchInput = document.getElementById('search');
245
fromEvent(searchInput, 'input').pipe(
246
map(event => event.target.value),
247
debounceTime(300) // Wait 300ms after user stops typing
248
).subscribe(searchTerm => {
249
console.log('Search for:', searchTerm);
250
// Perform search here
251
});
252
```
253
254
### throttleTime
255
256
Emit values at most once per time period.
257
258
```typescript { .api }
259
/**
260
* Emit values at most once per specified time period
261
* @param duration - Throttle duration in milliseconds
262
* @param scheduler - Optional scheduler
263
* @param config - Throttle configuration
264
* @returns Operator function throttling by time
265
*/
266
function throttleTime<T>(
267
duration: number,
268
scheduler?: SchedulerLike,
269
config?: ThrottleConfig
270
): OperatorFunction<T, T>;
271
272
interface ThrottleConfig {
273
leading?: boolean;
274
trailing?: boolean;
275
}
276
```
277
278
**Usage Examples:**
279
280
```typescript
281
import { fromEvent, throttleTime } from "rxjs";
282
283
// Throttle mouse moves
284
fromEvent(document, 'mousemove').pipe(
285
throttleTime(100) // At most once per 100ms
286
).subscribe(event => {
287
console.log('Mouse position:', event.clientX, event.clientY);
288
});
289
290
// Throttle with trailing emission
291
fromEvent(button, 'click').pipe(
292
throttleTime(1000, undefined, { leading: true, trailing: true })
293
).subscribe(() => console.log('Button clicked (throttled)'));
294
```
295
296
### takeUntil
297
298
Take values until another observable emits.
299
300
```typescript { .api }
301
/**
302
* Take values until notifier observable emits
303
* @param notifier - Observable that terminates the source
304
* @returns Operator function taking until notifier emits
305
*/
306
function takeUntil<T>(notifier: ObservableInput<any>): OperatorFunction<T, T>;
307
```
308
309
**Usage Examples:**
310
311
```typescript
312
import { interval, fromEvent, takeUntil } from "rxjs";
313
314
// Take interval values until button click
315
const stop$ = fromEvent(document.getElementById('stop'), 'click');
316
317
interval(1000).pipe(
318
takeUntil(stop$)
319
).subscribe(x => console.log('Timer:', x));
320
// Stops when stop button is clicked
321
```
322
323
### takeWhile
324
325
Take values while condition is true.
326
327
```typescript { .api }
328
/**
329
* Take values while predicate returns true
330
* @param predicate - Function returning boolean condition
331
* @param inclusive - Whether to include value that failed predicate
332
* @returns Operator function taking while condition is true
333
*/
334
function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive?: boolean): OperatorFunction<T, T>;
335
```
336
337
**Usage Examples:**
338
339
```typescript
340
import { of, takeWhile } from "rxjs";
341
342
// Take while less than 5
343
of(1, 2, 3, 4, 5, 6, 7).pipe(
344
takeWhile(x => x < 5)
345
).subscribe(x => console.log(x)); // 1, 2, 3, 4
346
347
// Include the failing value
348
of(1, 2, 3, 4, 5, 6, 7).pipe(
349
takeWhile(x => x < 5, true)
350
).subscribe(x => console.log(x)); // 1, 2, 3, 4, 5
351
```
352
353
### skipUntil and skipWhile
354
355
```typescript { .api }
356
/**
357
* Skip values until notifier observable emits
358
* @param notifier - Observable that starts emitting values
359
* @returns Operator function skipping until notifier emits
360
*/
361
function skipUntil<T>(notifier: ObservableInput<any>): OperatorFunction<T, T>;
362
363
/**
364
* Skip values while predicate returns true
365
* @param predicate - Function returning boolean condition
366
* @returns Operator function skipping while condition is true
367
*/
368
function skipWhile<T>(predicate: (value: T, index: number) => boolean): OperatorFunction<T, T>;
369
```
370
371
### elementAt and single
372
373
```typescript { .api }
374
/**
375
* Emit value at specific index
376
* @param index - Zero-based index of desired value
377
* @param defaultValue - Default value if index not found
378
* @returns Operator function emitting value at index
379
*/
380
function elementAt<T>(index: number): OperatorFunction<T, T>;
381
function elementAt<T, D>(index: number, defaultValue: D): OperatorFunction<T, T | D>;
382
383
/**
384
* Emit single value that matches predicate
385
* @param predicate - Optional predicate function
386
* @returns Operator function emitting single matching value
387
*/
388
function single<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, T>;
389
```
390
391
### defaultIfEmpty and isEmpty
392
393
```typescript { .api }
394
/**
395
* Emit default value if the source observable is empty
396
* @param defaultValue - Value to emit if source is empty
397
* @returns Operator function providing default value
398
*/
399
function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R>;
400
401
/**
402
* Emit true if source is empty, false otherwise
403
* @returns Operator function checking if source is empty
404
*/
405
function isEmpty<T>(): OperatorFunction<T, boolean>;
406
```
407
408
**Usage Examples:**
409
410
```typescript
411
import { EMPTY, of, defaultIfEmpty, isEmpty } from "rxjs";
412
413
// Empty source gets default value
414
EMPTY.pipe(
415
defaultIfEmpty('No data available')
416
).subscribe(x => console.log(x)); // 'No data available'
417
418
// Non-empty source passes through
419
of(1, 2, 3).pipe(
420
defaultIfEmpty('No data')
421
).subscribe(x => console.log(x)); // 1, 2, 3
422
423
// Check if empty
424
of(1, 2, 3).pipe(isEmpty()).subscribe(x => console.log('Empty:', x)); // false
425
EMPTY.pipe(isEmpty()).subscribe(x => console.log('Empty:', x)); // true
426
```
427
428
### Advanced Filtering
429
430
```typescript { .api }
431
/**
432
* Sample values when another observable emits
433
* @param notifier - Observable that triggers sampling
434
* @returns Operator function sampling on notifier emissions
435
*/
436
function sample<T>(notifier: ObservableInput<any>): OperatorFunction<T, T>;
437
438
/**
439
* Sample values at regular time intervals
440
* @param period - Sample period in milliseconds
441
* @param scheduler - Optional scheduler
442
* @returns Operator function sampling by time
443
*/
444
function sampleTime<T>(period: number, scheduler?: SchedulerLike): OperatorFunction<T, T>;
445
446
/**
447
* Audit values using another observable
448
* @param durationSelector - Function returning observable for audit duration
449
* @returns Operator function auditing with duration selector
450
*/
451
function audit<T>(durationSelector: (value: T) => ObservableInput<any>): OperatorFunction<T, T>;
452
453
/**
454
* Audit values for specified time duration
455
* @param duration - Audit duration in milliseconds
456
* @param scheduler - Optional scheduler
457
* @returns Operator function auditing by time
458
*/
459
function auditTime<T>(duration: number, scheduler?: SchedulerLike): OperatorFunction<T, T>;
460
461
/**
462
* Ignore all emitted values, only pass through completion and error
463
* @returns Operator function ignoring all values
464
*/
465
function ignoreElements<T>(): OperatorFunction<T, never>;
466
467
/**
468
* Find first emission matching predicate
469
* @param predicate - Predicate function to match emissions
470
* @param defaultValue - Default value if no match found
471
* @returns Operator function emitting first matching value
472
*/
473
function find<T>(predicate: (value: T, index: number) => boolean, defaultValue?: T): OperatorFunction<T, T | undefined>;
474
475
/**
476
* Find index of first emission matching predicate
477
* @param predicate - Predicate function to match emissions
478
* @returns Operator function emitting index of first match
479
*/
480
function findIndex<T>(predicate: (value: T, index: number) => boolean): OperatorFunction<T, number>;
481
482
/**
483
* Skip last n emissions
484
* @param skipCount - Number of emissions to skip from end
485
* @returns Operator function skipping last emissions
486
*/
487
function skipLast<T>(skipCount: number): OperatorFunction<T, T>;
488
489
/**
490
* Take last n emissions
491
* @param count - Number of emissions to take from end
492
* @returns Operator function taking last emissions
493
*/
494
function takeLast<T>(count: number): OperatorFunction<T, T>;
495
496
/**
497
* Get element at specified index
498
* @param index - Index of element to get
499
* @param defaultValue - Default value if index out of bounds
500
* @returns Operator function emitting element at index
501
*/
502
function elementAt<T>(index: number, defaultValue?: T): OperatorFunction<T, T>;
503
504
/**
505
* Test if observable is empty
506
* @returns Operator function emitting boolean indicating if empty
507
*/
508
function isEmpty<T>(): OperatorFunction<T, boolean>;
509
510
/**
511
* Emit only single value, error if more than one
512
* @param predicate - Optional predicate to filter single value
513
* @returns Operator function emitting single value
514
*/
515
function single<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, T>;
516
```
517
518
## Types
519
520
```typescript { .api }
521
interface ThrottleConfig {
522
leading?: boolean;
523
trailing?: boolean;
524
}
525
526
type OperatorFunction<T, R> = (source: Observable<T>) => Observable<R>;
527
type MonoTypeOperatorFunction<T> = OperatorFunction<T, T>;
528
```