2016-09-26 18 views
0

我想通過名稱從文件中檢索特定的城市。如果未找到該城市,則返回Observable.empty();否則我會返回Observable.just(城市); 下面是代碼:RxJava:在Observable.just之後它仍然調用Observable.empty()

public void onAddButtonClick(String cityName) { 
     Subscription subscription = repository.getCity(cityName)   
       .subscribeOn(backgroundThread) 
       .flatMap(city -> repository.saveCityToDb(city)) 
       .observeOn(mainThread)  
       .subscribe(
         city -> view.cityExists(), 
         throwable -> view.showCouldNotFindCity(), 
         () -> view.showCouldNotFindCity() 
       ); 

     subscriptions.add(subscription); 
    } 

和方法getCity()

public Observable<City> getCity(String cityName){ 
     return Observable.defer(() -> { 
      try { 
       InputStream is = assetManager.open(FILE_NAME); 
       Scanner scanner = new Scanner(is); 
       while (scanner.hasNextLine()) { 
        String line = scanner.nextLine(); 
        if (line.toLowerCase().contains(cityName.toLowerCase())) { 
         String[] cityParams = line.split("\t"); 
         City city = new City(); 
         city.setId(Long.parseLong(cityParams[0])); 
         city.setName(cityParams[1]); 
         return Observable.just(city); 
        } 
       } 

      } catch (IOException e) { 
       return Observable.error(e); 
      }   
      return Observable.empty(); 
     }); 
    } 

但是,當城市發現的問題是,它去return Observable.empty();我不知道爲什麼它返回Observable.just(city);。所以代碼() -> view.showCouldNotFindCity()被稱爲無論如何。

+2

除非出現錯誤,'view.showCouldNotFindCity()'將始終被調用。這不是你想要的嗎? – Will

+0

@但我想要有兩個選擇:如果找到了城市,並且沒有找到城市。代碼根據rusult而不同。什麼是最好的方式來做到這一點? – alla

回答

1

問題是你在onCompleted處理程序中調用this() - > view.showCouldNotFindCity()。如果你看看RxJava中的just()方法,你會看到它首先調用onNext,然後調用訂閱者上的onCompleted方法。所以當發現城市時 - > view.cityExists()被調用,然後立即在() - > view.showCouldNotFindCity()之後。

如果在您的getCity方法中找不到城市,我只會拋出一個錯誤。由於你的onError已經調用了desired() - > view.showCouldNotFindCity()方法並將它從onCompleted處理程序中移除。

+0

謝謝你的回答。但是什麼時候可以使用Observable.empty();如果() - > view.showCouldNotFindCity()被調用嗎?在什麼情況下? – alla

+0

通常您在onNext處理函數中處理事件流,並使用onCompleted進行清理。當你不用onNext推動任何東西時,你可以使用空的,而不是立即完成流。 –

相關問題