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
dotansimha authored and DAB0mB committed Mar 23, 2017
1 parent 3d165ed commit b303dee
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/pages/messages/messages.ts
Expand Up @@ -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',
Expand All @@ -20,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 @@ -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 {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit b303dee

Please sign in to comment.