Home > Enterprise >  How to Get the last element in Array list of Observable?
How to Get the last element in Array list of Observable?

Time:02-21

This function is to filter an observable off all message from my friend list (onlineUserModel) and to get an observable of type string; lastMessage of each friend

getLastMessage(onlineUserModel : OnlineUserModel): Observable<string>{
    var messagesFriend= this.allDirectMessages$.pipe(map(x => x.filter(f=>f.fromOnlineUser.userName==onlineUserModel.userName)));
    this.lastMessage$ = czt.pipe(map(last()))
    return ...;
  }

lastMessage is Obserbable of string from DirectMessage.messageModel.content; it is a string because if the message is a picture or voice i create a standard message; you have recieved a picture or ...

lastMessage$ : Observable<string>
allDirectMessages$ : Observable<DirectMessage[]> 
 <ul
              
              *ngFor="let onlineusermodel of onlineUsersModel$ | async"
              (click)="
                selectChat(onlineusermodel);
                removeNotificationForUser(onlineusermodel)
              "
            >
              <li >
                <div >
                  <img
                    [src]="onlineusermodel.profilePic"
                    
                    alt="image"
                  />
                </div>

                <div >
                  <div>
                    <h5>
                      {{ onlineusermodel.userName }}
                    </h5>
                    <p>getLastMessage(onlineUserModel)</p>
                  </div>
                  <div >
                    <small >05 min</small>
                    <div
                      *ngIf="{
                        count: getUserNotification(onlineusermodel) | async
                      } as data"
                    >
                      <div  *ngIf="data.count > 0">
                        {{ data.count }}
                        <!-- {{ getUserNotification(onlineusermodel) | async }} -->
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>

CodePudding user response:

Assuming they this.allDirectMessages$ emits an array of all dms in chronological order, I would think all you would need would be:

getLastMessage$({ userName }: OnlineUserModel): Observable<string> {
  return this.allDirectMessages$.pipe(
    map(dms => {
      const index = dms.findLastIndexOf(({fromOnlineUser}) => fromOnlineUser.userName === userName);
      if (index === -1) {
        return null;
      } else {
        return dms[index];
      }
    })
  );
}

... assuming this.allDirectMessages$ always completes. If it doesn't complete then the returned observable should also pipe takeUntil(this.destroy$) where destroy$ is a private Subject<void> and there's an ngOnDestroy of

ngOnDestroy(): void {
  const d$ = this.destroy$;
  if (d$) {
    d$.next();
    d$.complete();
  }
}
  • Related