1

BACKGROUND: I'm currently working on a mobile app that uses Promises and I'm exploring RxJS' Observables to replace all existing promise API calls. My understanding for async pipe is that it automatically unsubscribes when the ngOnDestroy is triggered. Since I am using Ionic Routing it does not trigger the ngOnDestroy it can only trigger ionViewWillLeave once I navigated to other page.

CODE: I implemented an async pipe in my html template that looks like this:

 <ng-container *ngIf="accounts$ | async as accounts; else loadingData">
  <app-account-card *ngFor="let account of accounts" [account]="account"></app-account-card>
</ng-container>

<!-- SKELETON -->
<ng-template #loadingData>
  <app-skeleton-account-card></app-skeleton-account-card>
</ng-template>

I have an account.service.ts that returns an Observable<Account[]>:

getAccountsObserver(): Observable<Account[]> {
try {
        return from(this.getSessionID()).pipe(
            switchMap(sessionId => this.http.get<Account[]>(`${URLS.accounts}${ENDPOINTS.accBalance}${sessionId}`))
        );
    } catch (e) {
        return null;
    }
}

For my account.component I simply declared a variable accounts$:

accounts$: Observable<Account[]>;

  constructor(
    private accountProvider: AccountProvider
  ) {}

  ngOnInit() {
    this.accounts$ = this.accountProvider.getAccountsObserver();
  }

QUESTION: Does the Async Pipe still unsubscribes? If no, how can I unsubscribe to it? Is Async Pipe still a best way to display a data from the API or do I need to find a different approach in my case?

dvbngln
  • 301
  • 2
  • 12
  • in case page is still in navigation stack (page above page...) then ngDestroy will not trigger unless the previous page is terminated... to terminate it u can use this.router.navigateByUrl('url', { replaceUrl: true }); but this could not work in case u need to go back to ur prev page... so better solution is go and do as this say https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription but still not sure if its the best case since i believe best solution is to set the unsubscribe function in ur service and call it when u want.. and ... – Mostafa Harb Jul 02 '22 at 10:52
  • and your approach using observables is not a good approach but i gave u some solutions for ur given but observables and events takes a lot of memory so u get data easier but face much performace issues when ur project expands and face more problems when u try to solve the performance issues when u need to unsubscribe and re subscribe to the event in case u need to navigate back or such things... – Mostafa Harb Jul 02 '22 at 10:54

0 Answers0