Learn RxJS
Search…
create

signature: create(subscribe: function)

Create an observable with given subscription function.

Examples

Example 1: Observable that emits multiple values
1
// RxJS v6+
2
import { Observable } from 'rxjs';
3
/*
4
Create an observable that emits 'Hello' and 'World' on
5
subscription.
6
*/
7
const hello = Observable.create(function(observer) {
8
observer.next('Hello');
9
observer.next('World');
10
observer.complete();
11
});
12
13
//output: 'Hello'...'World'
14
const subscribe = hello.subscribe(val => console.log(val));
Copied!
Example 2: Observable that emits even numbers on timer
1
// RxJS v6+
2
import { Observable } from 'rxjs';
3
4
/*
5
Increment value every 1s, emit even numbers.
6
*/
7
const evenNumbers = Observable.create(function(observer) {
8
let value = 0;
9
const interval = setInterval(() => {
10
if (value % 2 === 0) {
11
observer.next(value);
12
}
13
value++;
14
}, 1000);
15
16
return () => clearInterval(interval);
17
});
18
//output: 0...2...4...6...8
19
const subscribe = evenNumbers.subscribe(val => console.log(val));
20
//unsubscribe after 10 seconds
21
setTimeout(() => {
22
subscribe.unsubscribe();
23
}, 10000);
Copied!

Additional Resources

Last modified 1yr ago