diff --git a/src/pages/messages/messages.ts b/src/pages/messages/messages.ts index 5843e8faa..887e9003b 100644 --- a/src/pages/messages/messages.ts +++ b/src/pages/messages/messages.ts @@ -6,6 +6,7 @@ import { MeteorObservable } from 'meteor-rxjs'; import * as moment from 'moment'; import { _ } from 'meteor/underscore'; import { MessagesOptionsComponent } from './messages-options'; +import { Subscription } from 'rxjs'; @Component({ selector: 'messages-page', @@ -20,6 +21,8 @@ export class MessagesPage implements OnInit, OnDestroy { autoScroller: MutationObserver; scrollOffset = 0; senderId: string; + loadingMessages: boolean; + messagesComputation: Subscription; constructor( navParams: NavParams, @@ -53,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 { @@ -113,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