angularrxjsobservable

Why is this returning a subscription instead of an observable?


I have a function that adds an item to my list, it returns an observable that I can display some data

  add() {

    let data$ = of(this.data);

    data$.subscribe((val: any) => {
      let newData = {
        id: val.length + 1,
        description: `description ${val.length + 1}`,
        completed: false
      }

      this.data.push(newData);

      // this.list$.next(addMe);
      console.log(this.data);
      console.log(val.length);

    });

return data$;

}

But when I refactor it like this, it no longer works, it says data$ is a subscription now instead of an observable, but I don't understand how they aren't equivalent.

add(){

    let data$ = of(this.data).subscribe((val: any) => {
      let newData = {
        id: val.length + 1,
        description: `description ${val.length + 1}`,
        completed: false
      }

      this.data.push(newData);

      // this.list$.next(addMe);
      console.log(this.data);
      console.log(val.length);

    });

    return data$;

}

Solution

  • The output from a subscribe method, is always a subscription, which you can use to unsubscribe to the observable stream at a later point.


    My guess is that your add method, needs to return an observable after the data has been appeneded to it.

    You should instead use a BehaviourSubject to store the actual array, and firing the next method, when you perform any new operation, so the code will look below.

    data$ = new BehaviourSubject([]);
    
    add(){
    
        let data$ = of(this.data).subscribe((val: any) => { // <- try getting rid of the subscribe instead access the latest data using this.data$.value
          let newData = {
            id: val.length + 1,
            description: `description ${val.length + 1}`,
            completed: false
          }
          const transformedData = [ ...this.data$.value, newData ];
          this.data$.next(transformedData);
        });
        return this.data$;
    }