@@ -4,13 +4,14 @@ import { User } from 'api/models';
44import { AlertController , ViewController } from 'ionic-angular' ;
55import { MeteorObservable } from 'meteor-rxjs' ;
66import * as _ from 'lodash' ;
7- import { Observable , Subscription } from 'rxjs' ;
7+ import { Observable , Subscription , BehaviorSubject } from 'rxjs' ;
88
99@Component ( {
1010 selector : 'new-chat' ,
1111 templateUrl : 'new-chat.html'
1212} )
1313export class NewChatComponent implements OnInit {
14+ searchPattern : BehaviorSubject < any > ;
1415 senderId : string ;
1516 users : Observable < User [ ] > ;
1617 usersSubscription : Subscription ;
@@ -20,10 +21,28 @@ export class NewChatComponent implements OnInit {
2021 private viewCtrl : ViewController
2122 ) {
2223 this . senderId = Meteor . userId ( ) ;
24+ this . searchPattern = new BehaviorSubject ( undefined ) ;
2325 }
2426
2527 ngOnInit ( ) {
26- this . loadUsers ( ) ;
28+ this . observeSearchBar ( ) ;
29+ }
30+
31+ updateSubscription ( newValue ) {
32+ this . searchPattern . next ( newValue ) ;
33+ }
34+
35+ observeSearchBar ( ) : void {
36+ this . searchPattern . asObservable ( )
37+ // Prevents the search bar from being spammed
38+ . debounce ( ( ) => Observable . timer ( 1000 ) )
39+ . forEach ( ( ) => {
40+ if ( this . usersSubscription ) {
41+ this . usersSubscription . unsubscribe ( ) ;
42+ }
43+
44+ this . usersSubscription = this . subscribeUsers ( ) ;
45+ } ) ;
2746 }
2847
2948 addChat ( user ) : void {
@@ -39,12 +58,12 @@ export class NewChatComponent implements OnInit {
3958 } ) ;
4059 }
4160
42- loadUsers ( ) : void {
61+ subscribeUsers ( ) : Subscription {
4362 // Fetch all users matching search pattern
44- const subscription = MeteorObservable . subscribe ( 'users' ) ;
63+ const subscription = MeteorObservable . subscribe ( 'users' , this . searchPattern . getValue ( ) ) ;
4564 const autorun = MeteorObservable . autorun ( ) ;
4665
47- Observable . merge ( subscription , autorun ) . subscribe ( ( ) => {
66+ return Observable . merge ( subscription , autorun ) . subscribe ( ( ) => {
4867 this . users = this . findUsers ( ) ;
4968 } ) ;
5069 }
0 commit comments