2017-11-29 5 views
0

비 반응 코드를 Reactive Code로 연결하는 시나리오가 있습니다.반복 가능한 코드에서 벗어남 성공적인 응답시 관찰 가능

다음 시나리오를 고려하십시오.

ArrayList에는 3 개의 URL 목록이 있습니다. 각 URL을 ArrayList 안에있는 순서대로 호출하고 싶습니다. 한 번에 한 URL 만 호출 할 수 있습니다. 첫 번째 URL에서 응답이 성공적으로 반환되면 onComplete()에 전화를 걸고 나머지 URL을 실행하고 싶습니다. 그러나 응답이 오류 인 경우 목록에서 다음 URL을 실행하려고합니다. 이전 URL에 대한 오류 응답을받지 못하면 RxJava가 flatMap을 다음 URL로 호출하는 것을 원하지 않습니다. RxJava에 대한 나의 원시적 인 이해 때문에 이것을 성취 할 방법을 찾지 못했습니다.

나는 이런 식으로 뭔가 할 계획 무엇 :

Observable.fromIteratable(urlList) 
.subscribeOn(Schedulars.io()) 
.flatMap(new Func(String url, String data) { 
    SomeNetworkLibrary.getData(url) 
    .OnResponse(new NewResponse() { 
     public void onSuccess(String dataFromInternet) {return dataFromInternet;} 
     public void onError(String errorMessage) {return errorMessage;) 
    }) 
    // wait until we have response from the network call above and then return 
    // I don't know what will be the cleanest and efficient way of waiting here. 
}); 

TLDR을;

flatMap()의 결과가 반환되기 전에 flatMap()을 호출하고 싶지 않습니다.

어떻게하면됩니까?

답변

0

당신은 Observable에 네트워크 API 호출을 끈 다음 평평하게 한 후 take(1)를 사용할 수 있습니다

Observable.fromIteratable(urlList) 
.subscribeOn(Schedulars.io()) 
.concatMapDelayError((String url, String data) -> { 
    return Observable.create(emitter -> { 
     SomeNetworkLibrary.getData(url) 
     .OnResponse(new NewResponse() { 
      public void onSuccess(String dataFromInternet) { 
       emitter.onNext(dataFromInternet); 
       // don't call emitter.onComplete() so that 
       // concatMapDelayError doesn't switch to the next source 
      } 
      public void onError(String errorMessage) { 
       emitter.onError(errorMessage); 
      } 
     ); 
    }); 
    // wait until we have response from the network call above and then return 
    // I don't know what will be the cleanest and efficient way of waiting here. 
}) 
.take(1);