0

I am using events to subscribe an event in my ionic 3 application. It seems there are two ways to unsubscribe the subscription as given in the unsubscription1() and unsubscription2()

Could you please tell what is the difference of these two methods? are both of them can unsubscribe the subscription as expected?

import { Events } from 'ionic-angular'; ... messageSubscription: any constructor(private events: Events ...){ ... } subscription(){ messageSubscription = this.events.subscription("newmessage", () => { ... } } unsubscription1(){ this.events.unsubscription("newmessage") } unsubscription2(){ messageSubscription.unsubscribe() } 

2 Answers 2

2

Declare a variable for destroy condition

public destroyed = new Subject(); 

Add ngDestroy lifecycle hook

ngOnDestroy() { this.destroyed.next(); this.destroyed.complete(); } 

And use takeUntil(). Using an operator like takeUntil instead of manually unsubscribing will also complete the observable, triggering any completion event on the observable.

 this.events. .pipe(takeUntil(this.destroyed)) subscription("newmessage", () => { ... } 
Sign up to request clarification or add additional context in comments.

Comments

1
  • As per the Ionic Documentation, there are no .subscription and .unsubscription methods on Events
  • There are only .subscribe(<eventname>, () => {}) and .unsubscribe(<eventname>, () => {})
  • this.events.subscribe(<event>, () => {}) return type is void.
  • So messageSubscription variable holds nothing and events won't get unsubscribed in the below code

unsubscription2() { messageSubscription.unsubscribe(); }

So the correct code for subscribing and unsubscribing is below

import { Events } from 'ionic-angular'; ... constructor(private events: Events...) { ... } subscription() { this.events.subscribe("newmessage", () => { ... }); } unsubscription1() { this.events.unsubscribe("newmessage") } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.