The basic pattern of the observable or observer, and has two parts:
- The observable itself, that is, the object hat emits changes to any observer that wants to listen to it
- The observers, objecst who get called any time the observable emits a change
import { Observable, Subscription } from 'rxjs';
const customObservable = new Observable( (observer) => {
let count = 0;
setInterval( () => {
if( count === 70 )
observer.error( new Error( count + ' is found' ) );
if( count === 13 )
observer.complete();
observer.next( count );
count++;
}, 1000 );
});
this.subscription = customObservable.subscribe( (count) => {
console.log( 'the value of count is ', count );
}, (error) => {
console.log( error );
}, () => {
console.log( 'observable is finalized' );
});
import { Observable, Subscription, map } from 'rxjs';
const customObservable = new Observable( (observer) => {
let count = 0;
let stopIntervalValue = null;
stopIntervalValue = setInterval( () => {
console.log( "## count: ", count );
if( count === 70 )
observer.error( new Error( count + ' is found' ) );
if( count === 13 ){
observer.complete();
clearInterval( stopIntervalValue );
}
observer.next( count );
count++;
}, 1000 );
});
const pipedObservable = customObservable.pipe( map( (data : number) => {
return 'Round: ' + (data + 1);
}) );
this.subscription = pipedObservable.subscribe({
next : (count) => {
console.log( 'the value of count is ', count );
},
error : (error) => {
console.log( error );
},
complete : () => {
console.log( 'observable is finalized' );
}
});