From 44bf12a83f6f8cbb61aca2d4b9b12c619e38cea3 Mon Sep 17 00:00:00 2001 From: dotansimha Date: Tue, 24 Jan 2017 19:47:55 +0200 Subject: [PATCH] Step 10.5: Implement the search bar logic with RxJS --- src/pages/chats/new-chat.ts | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/pages/chats/new-chat.ts b/src/pages/chats/new-chat.ts index 1ddec6c96..aeda22ce3 100644 --- a/src/pages/chats/new-chat.ts +++ b/src/pages/chats/new-chat.ts @@ -4,13 +4,14 @@ import { User } from 'api/models'; import { AlertController, ViewController } from 'ionic-angular'; import { MeteorObservable } from 'meteor-rxjs'; import * as _ from 'lodash'; -import { Observable, Subscription } from 'rxjs'; +import { Observable, Subscription, BehaviorSubject } from 'rxjs'; @Component({ selector: 'new-chat', templateUrl: 'new-chat.html' }) export class NewChatComponent implements OnInit { + searchPattern: BehaviorSubject; senderId: string; users: Observable; usersSubscription: Subscription; @@ -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 { @@ -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(); }); }