Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Rxjs subject in ionic in details

In this post, we are going to introduce the Rxjs subject in ionic and how we can use them in Ionic 5 of the Angular project. Observables are unicasting. It means all subscribers get a new instance of observable. A regular observable does not have the next() method as regular observable ‘s are not observers. We can use the subject to emit data.

The second Subjects in RxJS are multicasting. A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. Internally to the Subject, subscribe does not invoke a new execution that delivers values. It simply registers the given Observer in a list of Observers, similarly to how addListener usually works in other libraries and languages.

The RXJS offers different types of Subjects, namely: BehaviorSubject, ReplaySubject, and AsyncSubject.

BehaviorSubject:  A subject that stores the latest value, and immediately sends it to new subscribers. It means even after a subscription, you can access its current value unless a value is erased with a new entry.

ReplaySubject: Replay subjects store a user-specific number of values for user-specified time. Up to the time, you could access those values.

AsyncSubject:  A subject that waits until it is complete, then sends the final value to any subscribers (even latecomers).

The subject is both an observable and an observer.
Observer — it has the next, error, and complete methods.
Observable — it has all the observable operators, and you can subscribe to him.

Rxjs subject in ionic example

In this example we will use a simple subject, whenever we add or delete a course in a courses array object, it will update its latest state of courses variable to the subject’s subscribers will, in turn, receive that pushed data.

Rxjs subject in ionic
Rxjs subject in ionic

We have a courseService provider, where we have a variable called courses containing the value of all courses. Every Subject is an Observer. It is an object with the methods next(v), error(e), and complete(). To feed a new value to the Subject, just call next(theValue), and it will be multicasted to the Observers registered to listen to the Subject.

In the example below, we have can add or delete course objects from the courses variable, when we are adding or deleting a course, will call the next method on Subject and we feed the current state of course list object to the Subject:

Step 1: Create project for Rxjs subject in Ionic

ionic start rxjsSubjectApp blank --type=angular
cd rxjsSubjectApp

Step 2: Create CourseService provider in our project as

ionic generate service course

Add following code in course.service.ts file

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CourseService {
  courses = [
    { name: 'Nodejs', type: 'Free' },
    { name: 'Angular', type: 'Premium' },
    { name: 'Java', type: 'Premium' }
  ];
  currentCourse = new Subject<any[]>();

  constructor() { }

  addCourse(course) {
    this.courses.push(course);
    /* do something with the value */
    this.currentCourse.next(this.courses);
  }

  deleteCourse(course) {
    this.courses = this.courses.filter((item) => {
      return item.name !== course.name;
    });
    /* do something with the value */
    this.currentCourse.next(this.courses);
  }

}

In our course.service.ts file, we need to import the Subject from Rxjs Library. In our course.service we add currentCourse variable of type Subject containing a list of courses in the latest state.  So whenever we are adding or deleting are emitting event by calling next on currentCourse by feed the latest state of courses as a parameter in the next method. In home.page we are subscribing to currentCourse.

Step 3: In the home page template we have a form for adding and deleting a new course. We also needed to import Subscription from Rxjs library. Add following code in home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Rxjs Subject
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-card class="ion-padding ion-text-center">
    <ion-text color="primary">Add Course Name</ion-text>
    <ion-item>
      <ion-label>Course</ion-label>
      <ion-input [(ngModel)]="newCourse.name" placeholder="course name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="floating">Type</ion-label>
      <ion-select [(ngModel)]="newCourse.type">
        <ion-select-option value="Free">Free</ion-select-option>
        <ion-select-option value="Premium">Premium</ion-select-option>
      </ion-select>
    </ion-item>
    <ion-button class="ion-float-right" shape="round" (click)="addCourse()">Add</ion-button>
  </ion-card>

  <ion-list>
    <ion-item-sliding *ngFor="let course of courses">
      <ion-item-options side="start">
        <ion-item-option color="danger" (click)="deleteCourse(course)">Delete</ion-item-option>
      </ion-item-options>
      <ion-item>
        <ion-label>{{ course.name }} : {{ course.type }}</ion-label>
      </ion-item>

    </ion-item-sliding>
  </ion-list>
</ion-content>

Add following code in home.page.ts file.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { CourseService } from '../course.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy {
  courses: any[];
  newCourse = { name: '', type: ''};
  private courseListSub: Subscription;

  constructor(private courseService: CourseService) { }

  ngOnInit() {
    this.courses = this.courseService.courses;
    this.courseListSub = this.courseService.currentCourse.subscribe((courses) => {
      this.courses = courses;
    });
  }

  addCourse() {
    this.courseService.addCourse(this.newCourse);
  }

  deleteCourse(course) {
    this.courseService.deleteCourse(course);
  }

  ngOnDestroy() {
    this.courseListSub.unsubscribe();
  }

}

We will import the CourseService provider on our page and we need to unsubscribe the subscription so we have called unsubscribe on courseListSub variable.

Check more information on the Rxjs subject in ionic angular on official Rxjs documentation.

Related posts

Rxjs subject in ionic in details

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top