Event.subscribe can be called from two places


#1

We have a home page, on the home page we show count in card.
This counter was split out because we use the same thing on a different page.
Two pages have this same count.card.

We added the pull down to refresh on both of these pages.
The page then calls the even so the count.card fires the event and pulls new data.

The problem is when we setup to subscribe to the even when the card is loaded (with the home page comes up).
But when second page is loaded it also calls the count.card code and subscribes to the even again.

How to handle event.subscribe when it its used on two different pages?


#2

It’s really confusing to read textual descriptions of code. I’m sure they make perfect sense to you, but not to anybody who hasn’t actually seen the code in question.

So all I can do is to describe how I would do this:

class CountService {
  private _count$ = new BehaviorSubject<number>(0);
  count$: Observable<number>;
  constructor() {
    this.count$ = this._count$.asObservable();
  }
  updateCount(nc: number): void {
    this._count$.next(nc);
  }
}

class Page1 {
  count = 0;
  private _countsub: Subscription | null = null;
  constructor(private _countsvc: CountService) {
  }
  ionViewWillEnter(): void {
    this._countsub = this._countsvc.count$.subscribe(count => this.count = count);
  }
  ionViewWillLeave(): void {
    if (this._countsub) {
      this._countsub.unsubscribe();
      this._countsub = null;
    }
  }
  incrementCount(): void {
    this._countsvc.updateCount(this.count + 1);
  }
} 

class Page2 {
  // everything relevant that is in Page1
}

#3

Thanks for that code. I think its close. The problem is the pages aren’t linear.
Home Page (root menu)
Has component on it called counter

Page 2
Same component counter

Counter Compoenent
Page loads
Event.subscribe to pull count

If data changes or refreshed this will pull the latest.

Home page loads, Counter component is called, with the subscribe.
This is the root page so its never unloaded unless the user logs out.

The user navigates to Page 2.
Counter component is called again, and second subscribe is setup.
If the user tries to do the pull down to refresh, the event is fired and because two are set up they both run their course.

The user clicks the home button (this clears any sub pages and starts nav stack over again).
I can’t unsubscribe because I still want the home component event to still work.

I’m more trying to stop the second subscribe from getting setup. Any variable that is inside the component seems to get initialized again. The component does know if its the first time it was called or the 10th.

I think this is not the normal use case for events.


#4

This conversation is not moving forward. Somebody else is going to have to take over.