ASYNC pipe not working on BehaviorSubject

Viewed 66

I'm trying to use Async pipe but when i trigger some new data to my BehaviorSubject, the value is not even fetch by the subject. If i change the async pipe by a manualy subscription, i receive the value but the view still not updated. I have to use manualy detectChange for this case.

Services:

@Injectable({
  providedIn: 'root',
})
export class WalletService {
  ethereum: any;
  currentAccountSubject: BehaviorSubject<any> = new BehaviorSubject([]);
  currentNetworkSubject: BehaviorSubject<any> = new BehaviorSubject(null);
  currentProviderSubject: BehaviorSubject<any> = new BehaviorSubject(null);
  constructor() {
    this.ethereum = (<any>window).ethereum;
    this.checkWalletConnected().subscribe();
    this.accountChanged();
    this.networkChanged();
  }

  private accountChanged(): void {
    this.ethereum.on('accountsChanged', (accounts: string[]) => {
      if(accounts.length === 0) this.currentProviderSubject.next(null);
      console.log('accountChanged', accounts) //WORKING FINE
      this.currentAccountSubject.next(accounts);
    });
  }
}

Components:

export class AppComponent implements OnInit{
  accounts$: Observable<string[]> = of([]);

  constructor(private walletService: WalletService) {}

  ngOnInit(): void {
    this.accounts$ = this.walletService.currentAccountSubject.pipe(
      skip(1),
      distinctUntilChanged((prev, curr) => prev[0] === curr[0]),
      tap(wallets => console.log('wallets', wallets)), //NOT WORKING WITH ASYNC PIPE BUT WORKING WHITOUT
    )

  }
}

HTLM: AppComponent:

<app-toolbar [accounts]="accounts$ | async"></app-toolbar>

ToolBarComponent:

<mat-toolbar>
  <span>
    <img src="/assets/mySvg.svg" alt="svg" />
  </span>
  <span class="spacer"></span>
  <ng-container *ngIf="accounts && accounts.length > 0; else btnConnect">{{accounts[0]}}</ng-container>
  <ng-template #btnConnect>
    <button mat-raised-button color="primary" (click)="connectToWallet()">Connect Wallet</button>
    </ng-template>
</mat-toolbar>

If you want to try yourself: https://stackblitz.com/edit/angular-xkrt7c?file=src/app/app.module.ts

1 Answers

The below line is the problem, ensure that unique value is being compared inside the distinctUntilUnchanged.

  distinctUntilChanged((prev, curr) => prev[0] === curr[0]), // <- problem here

You can try to fix it yourself if not please share a sample data for prev and curr inorder to resolve this issue and also provide the unique key inside accounts!

Related