diff --git a/client/imports/pages/messages/messages.ts b/client/imports/pages/messages/messages.ts index 08ba552..4eecaab 100644 --- a/client/imports/pages/messages/messages.ts +++ b/client/imports/pages/messages/messages.ts @@ -3,7 +3,7 @@ import { NavParams, PopoverController } from 'ionic-angular'; import { MeteorObservable } from 'meteor-rxjs'; import { _ } from 'meteor/underscore'; import * as Moment from 'moment'; -import { Observable } from 'rxjs'; +import { Observable, Subscription } from 'rxjs'; import { Messages } from '../../../../imports/collections'; import { Chat, Message, MessageType } from '../../../../imports/models'; import { MessagesOptionsComponent } from './messages-options'; @@ -21,6 +21,8 @@ export class MessagesPage implements OnInit, OnDestroy { autoScroller: MutationObserver; scrollOffset = 0; senderId: string; + loadingMessages: boolean; + messagesComputation: Subscription; constructor( navParams: NavParams, @@ -54,9 +56,32 @@ export class MessagesPage implements OnInit, OnDestroy { this.autoScroller.disconnect(); } - subscribeMessages() { + // Subscribes to the relevant set of messages + subscribeMessages(): void { + // A flag which indicates if there's a subscription in process + this.loadingMessages = true; + // A custom offset to be used to re-adjust the scrolling position once + // new dataset is fetched this.scrollOffset = this.scroller.scrollHeight; - this.messagesDayGroups = this.findMessagesDayGroups(); + + MeteorObservable.subscribe('messages', + this.selectedChat._id + ).subscribe(() => { + // Keep tracking changes in the dataset and re-render the view + if (!this.messagesComputation) { + this.messagesComputation = this.autorunMessages(); + } + + // Allow incoming subscription requests + this.loadingMessages = false; + }); + } + + // Detects changes in the messages dataset and re-renders the view + autorunMessages(): Subscription { + return MeteorObservable.autorun().subscribe(() => { + this.messagesDayGroups = this.findMessagesDayGroups(); + }); } showOptions(): void { @@ -114,6 +139,11 @@ export class MessagesPage implements OnInit, OnDestroy { } scrollDown(): void { + // Don't scroll down if messages subscription is being loaded + if (this.loadingMessages) { + return; + } + // Scroll down and apply specified offset this.scroller.scrollTop = this.scroller.scrollHeight - this.scrollOffset; // Zero offset for next invocation