2016-06-30 3 views
0

Google 인식 API를 사용하는 중 일부가 엉망이되어 RxJava에 대한 이해가 제한됩니다.Return 콜백에서 관찰 할 수 있습니다. rxjava

최종 목표 : Api에서 Weather와 Location을 가져 와서이를 업데이트 할 수있는 하나의 객체로 병합하고 싶습니다.

그러나 반환 유형이 void이고 api.getWeather 및 api.getLocation에서 날씨 및 위치 개체를 병합하는 방법을 알기 때문에 API 콜백에서 Observable을 반환하는 방법을 잘 모르겠습니다. 내 프로젝트에서 내 다른 것들에 대한

public void requestUserCurrentInfo() { 
    Subscription userInfo = getWeatherLocation().subscribeOn(Schedulers.io()) 
      .observeOn(AndroidSchedulers.mainThread()).subscribe(userinfo -> 
        Log.d(TAG,userinfo.something())); 
} 

public Observable<UserInfo> getWeatherLocation() { 
    try { 
     Awareness.SnapshotApi.getWeather(client) 
       .setResultCallback(weather -> { 
        if (!weather.getStatus().isSuccess()) { 
         Log.d(TAG, "Could not get weather"); 
         return; 
        } 
        //How do I do here? 
        return weather.getWeather(); 
       }); 


     Awareness.SnapshotApi.getLocation(mGoogleApiClient) 
      .setResultCallback(retrievedLocation -> { 
       if(!retrievedLocation.getStatus().isSuccess()) return; 
       Log.d("FRAG", retrievedLocation.getLocation().getLatitude() + ""); 
      }); 


    } catch (SecurityException exception) { 
     throw new SecurityException("No permission " + exception); 

    } 

} 

, 나는 모든 단계는 관찰 가능한 < SmhiResponse을 반환하기 때문에 나는이 같은 그것을 얻을 수, 저장소 패턴 다음은 REST API를 통해 물건을받을>

getWeatherSubscription = getWeatherUsecase.execute().subscribeOn(Schedulers.io()) 
      .observeOn(AndroidSchedulers.mainThread()).subscribe(
        smhiResponseModel -> {Log.d(TAG,"Retrieved weather"); locationView.hideLoading();}, 
        err -> {Log.d(TAG,"Error fetching weather"); locationView.hideLoading();} 
      ); 

답변

1

당신은 콜백에서 관찰을 반환하지만, 그들이 결합하기 위해 관찰 가능한로 (테스트되지 않은) 당신의 콜백을 포장하지 않는 관찰 가능한 :

Observable<WeatherResult> weatherObservable = Observable.create(subscriber -> { 
     Awareness.SnapshotApi.getWeather(client) 
       .setResultCallback(weather -> { 
        if (!weather.getStatus().isSuccess()) { 
         subscriber.onError(new Exception("Could not get weather.")); 
         Log.d(TAG, "Could not get weather"); 
        } else { 
         //How do I do here? 

         subscriber.onNext(weather); 
         subscriber.onCompleted(); 
        } 
       }); 
    }); 

    Observable<LocationResult> locationObservable = Observable.create(subscriber -> { 
     Awareness.SnapshotApi.getLocation(mGoogleApiClient) 
       .setResultCallback(retrievedLocation -> { 
        if(!retrievedLocation.getStatus().isSuccess()) { 
         subscriber.onError(new Exception("Could not get location.")); 
        } else { 
         Log.d("FRAG", retrievedLocation.getLocation().getLatitude() + ""); 
         subscriber.onNext(retrievedLocation); 
         subscriber.onCompleted(); 
        } 
       }); 
    }); 
지금

그들을 결합

Observable<CombinedResult> combinedResults = Observable.zip(weatherObservable, locationObservable, 
      (weather, location) -> { 
       /* somehow combine weather and location then return as type "CombinedResult" */ 
      }); 

그렇지 않으면 그들 중 누구도 실행되지 도착, 가입하는 것을 잊지 마세요 :

.combineLatest() 또는 .zip()를 통해
combinedResults.subscribe(combinedResult -> {/*do something with that stuff...*/}); 
+0

고맙습니다. 당신이 이것을 쓸 때 매우 매력적입니다. – buddhabath

+0

Z이 경우 구독 취소 관리는 어떻게해야하나요? – buddhabath

+0

종료 후 (예 : onError 또는 onCompleted가 구독자에서 실행 됨) unsubscribe wouldnt 어쨌든 모든 요소 (실제로는 그 중 하나)를 받았거나 오류가 발생했기 때문에 아무 것도하지 마십시오. –

0
Observable.combineLatest(getWeather(), getLocation(), new Func2<List<Object_A>, List<Object_B>, Object>() { 
      @Override 
      public Object call(Object o, Object o2) { 
       combine both results and return the combine result to observer 
      } 
     }) 
,

getweather()과의 getLocation() 반환

+0

당신이 의미하는 방법을 확실하지은 API의 실제 방법은 보이는 Awareness.SnapshotApi.getWeather (mGoogleApiClient) .setResultCallback (새 ResultCallback () { @Override 공공 무효 onResult (같은 @NonNull WeatherResult weatherResult) { if (! weatherResult.getStatus(). isSuccess()) { return; } 날씨 weather = weatherResult.getWeather(); } }); – buddhabath

+0

나는 getweather()와 getlocation()이 observable을 각각 반환해야 함을 의미하고 combinelatest를 사용하여이 두 observable을 하나의 observable로 병합합니다. –

+0

예 지금까지 저는 여러분과 함께 있지만 날씨 나 위치를 관찰 가능으로 반환하려고하면 불평합니다 . Observable.just (날씨) 또는 Observable.create ...로 어떻게 할 수 있습니까? – buddhabath

관련 문제