-1

I have cloned one Github repo based on RXJS with angular 2+. Help me understand the meaning of this.createTodo$.subscribe(this.create$) in below code.

I am able to understand that here we are trying to subscribe createTodo$ observable.Inside the subscribe method I always set data but what does this.create$ means.Here create$ is a Subject.

Please find the service code where this subscription is made.

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable ,Subject} from 'rxjs';
import {  itemmodel } from './models/listmodel';
import {scan,map} from 'rxjs/operators';

type TodosOperation = (todos: itemmodel[]) => itemmodel[];
const initialTodos=[];

@Injectable({
  providedIn: 'root'
})

export class SharedserviceService {
  public data;
  create$: Subject<itemmodel> = new Subject<itemmodel>();
  createTodo$: Subject<itemmodel> = new Subject<itemmodel>();
  todos$:Observable<itemmodel[]>;
  public item = new BehaviorSubject([]);
  update$: BehaviorSubject<TodosOperation> = new BehaviorSubject<TodosOperation>((todos: itemmodel[]) => todos);

  constructor(){ 
    this.todos$ = this.update$.pipe(scan((todos: itemmodel[], operation: TodosOperation) => operation(todos), initialTodos));

    this.create$.pipe(map((todo) => {
      return (todos) => todos.concat(todo);
    })).subscribe(this.update$);

    this.createTodo$.subscribe(this.create$);
  }

  public additem(item){
    this.createTodo$.next(item);
  }

}
  • A `Subject` is both an `Observable` and an `Observer`. `subscribe` takes an `Observer`, so it can be passed a `Subject`. – cartant Jan 02 '19 at 05:42
  • Thanks cartant! I have been looking for an easy article to understand it .Can you provide any useful link. – Suruchi Babbar Jan 02 '19 at 07:34
  • [On The Subject Of Subjects (in RxJS)](https://medium.com/@benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93) and [RxJS: Understanding Subjects](https://blog.angularindepth.com/rxjs-understanding-subjects-5c585188c3e1). – cartant Jan 02 '19 at 08:43

1 Answers1

0

it's a naming convention. Using te dollar sign ($) you indicate that the variable is a stream (observer).

to observe the stream, you subscribe to it

fransyozef
  • 544
  • 2
  • 7
  • 18