Skip to content

Commit

Permalink
Step 10.5: Implement the search bar logic with RxJS
Browse files Browse the repository at this point in the history
  • Loading branch information
dotansimha authored and DAB0mB committed Feb 13, 2017
1 parent 82574e5 commit 8d8cbe7
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions client/imports/pages/chats/new-chat.ts
Expand Up @@ -2,7 +2,7 @@ import { Component, OnInit } from '@angular/core';
import { AlertController, ViewController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { _ } from 'meteor/underscore';
import { Observable, Subscription } from 'rxjs';
import { Observable, Subscription, BehaviorSubject } from 'rxjs';
import { Chats, Users } from '../../../../imports/collections';
import { User } from '../../../../imports/models';
import template from './new-chat.html';
Expand All @@ -11,6 +11,7 @@ import template from './new-chat.html';
template
})
export class NewChatComponent implements OnInit {
searchPattern: BehaviorSubject<any>;
senderId: string;
users: Observable<User[]>;
usersSubscription: Subscription;
Expand All @@ -20,10 +21,28 @@ export class NewChatComponent implements OnInit {
private viewCtrl: ViewController
) {
this.senderId = Meteor.userId();
this.searchPattern = new BehaviorSubject(undefined);
}

ngOnInit() {
this.loadUsers();
this.observeSearchBar();
}

updateSubscription(newValue) {
this.searchPattern.next(newValue);
}

observeSearchBar(): void {
this.searchPattern.asObservable()
// Prevents the search bar from being spammed
.debounce(() => Observable.timer(1000))
.forEach(() => {
if (this.usersSubscription) {
this.usersSubscription.unsubscribe();
}

this.usersSubscription = this.subscribeUsers();
});
}

addChat(user): void {
Expand All @@ -39,12 +58,12 @@ export class NewChatComponent implements OnInit {
});
}

loadUsers(): void {
subscribeUsers(): Subscription {
// Fetch all users matching search pattern
const subscription = MeteorObservable.subscribe('users');
const subscription = MeteorObservable.subscribe('users', this.searchPattern.getValue());
const autorun = MeteorObservable.autorun();

Observable.merge(subscription, autorun).subscribe(() => {
return Observable.merge(subscription, autorun).subscribe(() => {
this.users = this.findUsers();
});
}
Expand Down

0 comments on commit 8d8cbe7

Please sign in to comment.