Skip to content
Polina Soshnin edited this page Jan 28, 2016 · 3 revisions

Use Case: A Search Bar

  • Whenever you create a search bar, you have to think about concurrent requests.
  • With a Promise based implementation, the displayed result would be what the longest promise returns. RxJs can be used to avoid this problem.
    /*************************************************************
    Without RxJS
    
    The following code is used to implement a search of users by location.

    - It depends on a promise-based (.then()) implementation.
    - The problem with a promise-based implemenation is that you can't control
    the time a promise takes to resolve.
    - What you'll find is that the UI won't display the latest query result;
    it will display the one that takes the longest to resolve first.
    - This is a known side effect of promises.

    function searchEntities(type){
      console.log('type', type);
      connectModel.getUsersByLocation(type).then(function(result) {
        vm.entities = result.data;
      });
    }

    $scope.$watch(function(){ 
      return vm.filters.entityType;
    }, function(newVal){
      if (newVal) {
        searchEntities(newVal);
      }
    });
    **************************************************************/

    /*************************************************************
    With RxJS/Observables

    - RxJS resolves our problem stated above
    - You no longer have to depend on how long it takes to resolve 
    promises.

    **************************************************************/

      var source = Rx.Observable.create(function(observer) {
        $scope.$watch(function(){ 
          return vm.filters.entityType;
        }, function(newVal){
            observer.onNext(newVal);
        });
      }).flatMapLatest(function(type) {
          return Rx.Observable.fromPromise(connectModel.getUsersByLocation(type));
        });

      var listener = source.subscribe(function(result) {
        console.log('go here');
        vm.entities = result.data;
      });

      //remove Rx listener on route change
      $scope.$on('$destroy', function() {
        listener.dispose();
      });
Clone this wiki locally