Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable.create(...).map is not a function

I just learn Pluralsight - Getting Started with Reactive Programming with RxJS

Why not work?

I use RXJS 6.2.0

import {Observable} from 'rxjs';

const numbers = [1, 5, 10];
const source = Observable.create(observer => {

  let index = 0;
  let produceValue = () => {
    observer.next(numbers[index++]);

    if (index < numbers.length) {
      setTimeout(produceValue, 2000);
    } else {
      observer.complete();
    }
  };

  produceValue();

}).map(n => n * 2)
  .filter(n => n > 4);

source.subscribe(
  value => console.log(`value: ${value}`),
  e => console.log(`error: ${e}`),
  () => console.log('complete')
);
like image 758
Rae Avatar asked Jun 04 '18 03:06

Rae


2 Answers

I was doing the same course and was able to solve this using pipe and typing the variable in the parameters of the arrow functions, in the following way:

...
let source = Observable.create(observer => {

    let index = 0;
    let produceValue = () => {

        observer.next(numbers[index++]);

        if (index < numbers.length) {
            setTimeout(produceValue, 250);
        } else {
            observer.complete();
        }
    }

    produceValue();
}).pipe(
    map((n: number) => n * 2),
    filter((n: number) => n > 4)
);
...

Requiring using operators inside of pipe is a recent change on the way RxJs works, so some courses and references may be out of date.

like image 184
Rodrigo Marcondes Avatar answered Oct 19 '22 23:10

Rodrigo Marcondes


as recommended on comment, you should use pipe now.

Your code edited :

import {Observable} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const numbers = [1, 5, 10];
const source = Observable.create(observer => {

  let index = 0;
  let produceValue = () => {
    observer.next(numbers[index++]);

    if (index < numbers.length) {
      setTimeout(produceValue, 2000);
    } else {
      observer.complete();
    }
  };

  produceValue();

}).pipe(map<number, number>(n => n * 2),filter(n => n > 4)); // Here we pipe operators, you can provide any number of operators. or chain many pipe. 

source.subscribe(
  value => console.log(`value: ${value}`),
  e => console.log(`error: ${e}`),
  () => console.log('complete')
);

online sample

like image 30
Yanis-git Avatar answered Oct 19 '22 22:10

Yanis-git