简体   繁体   中英

Rxjs using Observable.from() string and prevent Observable being created many times

I have the following function that I'm trying to prevent Observable from being created every time this function is called. Basically, this function is called every time the user types something in the search field. I know I can create Observable from the event as Observable.fromEvent('button', click) but it would require me make tons of changes to the app. Any help is appreciated.

function search(input) { 
  Observable.from([input])
  .map(value => value)
  .filter(value => value.length >3)
  .debounceTime(300)
  .distinctUntilChanged()
  .switchMap(searchValue => { 
    //ajax call 
    return Promise.resolve(data) 
  }) 
  .subscribe(data => {
    //Do something with the data
  })
}

If you want to use observables, but don't want to create one from an event, you can create a Subject and can call its next method from within your search :

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

var searchSubject = new Subject();
  .filter(value => value.length > 3)
  .debounceTime(300)
  .distinctUntilChanged()
  .switchMap(searchValue => { 
    // ajax call
    return Promise.resolve(data) 
  }) 
  .subscribe(data => {
    // Do something with the data
  });

function search(input) { 
  searchSubject.next(input);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM