Skip to content

Commit

Permalink
Step 9.19: Subscribe to messages
Browse files Browse the repository at this point in the history
  • Loading branch information
DAB0mB committed Feb 13, 2017
1 parent b5c1c60 commit 788a2ce
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions client/imports/pages/messages/messages.ts
Expand Up @@ -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';
Expand All @@ -21,6 +21,8 @@ export class MessagesPage implements OnInit, OnDestroy {
autoScroller: MutationObserver;
scrollOffset = 0;
senderId: string;
loadingMessages: boolean;
messagesComputation: Subscription;

constructor(
navParams: NavParams,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 788a2ce

Please sign in to comment.