Skip to content

Commit e279343

Browse files
dotansimhadarkbasic
authored andcommitted
Step 9.19: Subscribe to messages
1 parent 53d5898 commit e279343

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

src/pages/messages/messages.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { MeteorObservable } from 'meteor-rxjs';
66
import * as moment from 'moment';
77
import * as _ from 'lodash';
88
import { MessagesOptionsComponent } from './messages-options';
9+
import { Subscription } from 'rxjs';
910

1011
@Component({
1112
selector: 'messages-page',
@@ -20,6 +21,8 @@ export class MessagesPage implements OnInit, OnDestroy {
2021
autoScroller: MutationObserver;
2122
scrollOffset = 0;
2223
senderId: string;
24+
loadingMessages: boolean;
25+
messagesComputation: Subscription;
2326

2427
constructor(
2528
navParams: NavParams,
@@ -53,9 +56,32 @@ export class MessagesPage implements OnInit, OnDestroy {
5356
this.autoScroller.disconnect();
5457
}
5558

56-
subscribeMessages() {
59+
// Subscribes to the relevant set of messages
60+
subscribeMessages(): void {
61+
// A flag which indicates if there's a subscription in process
62+
this.loadingMessages = true;
63+
// A custom offset to be used to re-adjust the scrolling position once
64+
// new dataset is fetched
5765
this.scrollOffset = this.scroller.scrollHeight;
58-
this.messagesDayGroups = this.findMessagesDayGroups();
66+
67+
MeteorObservable.subscribe('messages',
68+
this.selectedChat._id
69+
).subscribe(() => {
70+
// Keep tracking changes in the dataset and re-render the view
71+
if (!this.messagesComputation) {
72+
this.messagesComputation = this.autorunMessages();
73+
}
74+
75+
// Allow incoming subscription requests
76+
this.loadingMessages = false;
77+
});
78+
}
79+
80+
// Detects changes in the messages dataset and re-renders the view
81+
autorunMessages(): Subscription {
82+
return MeteorObservable.autorun().subscribe(() => {
83+
this.messagesDayGroups = this.findMessagesDayGroups();
84+
});
5985
}
6086

6187
showOptions(): void {
@@ -113,6 +139,11 @@ export class MessagesPage implements OnInit, OnDestroy {
113139
}
114140

115141
scrollDown(): void {
142+
// Don't scroll down if messages subscription is being loaded
143+
if (this.loadingMessages) {
144+
return;
145+
}
146+
116147
// Scroll down and apply specified offset
117148
this.scroller.scrollTop = this.scroller.scrollHeight - this.scrollOffset;
118149
// Zero offset for next invocation

0 commit comments

Comments
 (0)