0

I have created a observable that i am subscribing every time at button click event .

import {Component} from '@angular/core';
import {MainService} from '..\services\main-service';
@component({
 selector:'app-main',
 style:'',
 template:'<div> <button click="processing()">Processing</button></div>'   
})

exports class AppMain{

 constructor(private mainService: MainService){
}

processing(){
  this.mainService.process$.subscribe((res)=>{
    // doing something here ..
  }); 
}
}

MainService

import {OnInit} from '@angular\core'; 
import {Observable} from 'rxjs\Observable'; 
export class MainService implements OnInit{
   public process$;
   constructor(){
     this.process$ = new Observable((observer)=>{
         // doing something here
         observer.next();
     });
  }
}

Now whenever i click multiple times on this button sometimes this observable functionality run sometime not.

does i have to unsubscribe this observable after each subsciption or have to do something else

Sunny Goel
  • 1,982
  • 2
  • 15
  • 21
  • Can you also show `MainService` class implementation? And your subscription call back will run only when event is emitted unless you are using `BehaviorSubject` – Amit Chigadani Dec 13 '18 at 07:09
  • 1
    @AmitChigadani can you please elaborate this statement `And your subscription call back will run only when event is emitted ` , because here `on click of button` event is emitted so why not it is calling here whenever button is pressed – Sunny Goel Dec 13 '18 at 07:16
  • @AmitChigadani MainService have `process$` Observable define only – Sunny Goel Dec 13 '18 at 07:17
  • On click of button you are subscribing to an `process$` event, not emitting the event. So multiple clicks will only create new `Subscriptions`. – Amit Chigadani Dec 13 '18 at 07:18
  • 1
    @AmitChigadani , if you see in every subscription am running the `observer.next()` so i think it should call the callback . am i write ? – Sunny Goel Dec 13 '18 at 07:26
  • I feel you have completely messed up angular concepts. If `MainService` is a service then you should not be implementing `OnInit()` there. Move all your code to `constructor` block. https://stackoverflow.com/questions/35110690/ngoninit-not-being-called-when-injectable-class-is-instantiated – Amit Chigadani Dec 13 '18 at 07:44
  • @AmitChigadani , yes i have added that in constructor block , here i type it by mistake . i know `ngOnInit` is a component lifecycle method , please elaborate your statement – Sunny Goel Dec 13 '18 at 07:55

1 Answers1

0

This is the solution which works for me. I follow this link it helps me .

following will be the solution of this problem.

processing(){
  const processUnsubscribe$;
  processUnsubscribe$ = this.mainService.process$.subscribe((res)=>{
  // doing something here ..

  //Now unsubscribe here if you subscribe this multiple times.
   processUnsubscribe$.unsubscribe();   
  });   
 }
}
Sunny Goel
  • 1,982
  • 2
  • 15
  • 21