- RxJS Tutorial
- RxJS - Home
- RxJS - Overview
- RxJS - Environment Setup
- RxJS - Latest Updates
- RxJS - Observables
- RxJS - Operators
- RxJS - Working with Subscription
- RxJS - Working with Subjects
- RxJS - Working with Scheduler
- RxJS - Working with RxJS & Angular
- RxJS - Working with RxJS & ReactJS
- RxJS Useful Resources
- RxJS - Quick Guide
- RxJS - Useful Resources
- RxJS - Discussion
RxJS - Creation Operator count
count() takes in an Observable with values and converts it into an Observable that will give a single value. The count function takes in predicate function as an optional argument. The function is of type boolean and will add value to the output only if the value is truthy.
Syntax
Here is the syntax for Count −
count(predicate_func? : boolean): Observable
Parameters
predicate_func − (optional) Function that will filter the values to be counted from the source observable and return a boolean value.
Return value
The return value is an observable that has the count of the given numbers.
Let us see some examples of count without predicate and with function.
Example 1
The following example is without predicate function −
import { of } from 'rxjs'; import { count } from 'rxjs/operators'; let all_nums = of(1, 7, 5, 10, 10, 20); let final_val = all_nums.pipe(count()); final_val.subscribe(x => console.log("The count is "+x));
Output
The count is 6
Example 2
The following example is with predicate function −
import { of } from 'rxjs'; import { count } from 'rxjs/operators'; let all_nums = of(1, 6, 5, 10, 9, 20, 40); let final_val = all_nums.pipe(count(a => a % 2 === 0)); final_val.subscribe(x => console.log("The count is "+x));
The function we have used in the count is to give the count only of even numbers.
Output
The count is 4
To Continue Learning Please Login
Login with Google