2016-10-02 1 views
2

은 내가 getUserID 호출 내가 getProfile에 대한 다음 호출에 사용하십시오 CompletionStage<String>을 반환Java 8에서 thenCompose의 결과를 여러 번 사용하는 방법은 무엇입니까?

myObject.updateDB(payload) 
     .thenCompose(__ -> getUserID(payload.ID())) 
     .thenCompose(id -> getProfile(id)) 
     .thenCompose(userProfile -> updateSomething(userProfile)) 
     .thenCompose(__ -> notifyUser(id)) 
     .thenAccept(__ -> doSomething()) 
     .exceptionally(t -> doSomethingElse()); 

유사 thenCompose 일련의 호출을 보유하고 있습니다. notifyUser 호출에 대해 다시 id이 필요합니다. 어떻게 사용 가능하게 만들 수 있습니까? IDE가 표시됩니다.

기호 ID를 해결할 수 없습니다.

답변

1

현재 코드 문제는 .thenCompose(__ -> notifyUser(id))에 도달하는 시간으로, 변수 id 더 이상 범위에 포함되지 것입니다.

이 경우 간단한 해결책은 getProfile에 의해 반환 된 CompletionStage에 직접 여러 thenCompose를 호출하는 것입니다 :

myObject.updateDB(payload) 
    .thenCompose(__ -> getUserID(payload.ID())) 
    .thenCompose(id -> 
     getProfile(id) 
      .thenCompose(userProfile -> updateSomething(userProfile)) 
      .thenCompose(__ -> notifyUser(id)) 
) 
    // rest of chain calls 
+0

합니다. 간단한 해결책은'구성 체인을 단일 코드 블록으로 전환하는 것입니다. 이렇게 많은 단계에서 전체적으로 선형의 시퀀스를 표현할 때 이점이 없다. 단일 액션으로 작성하면 필요한 모든 값이 범위에 있으며 사용하지 않은 모든 매개 변수가 사라집니다. – Holger

0

난 당신이 모든에 대한 thenCompose를 사용하여 주장하지 않는 경우 코드가, 간단하게, 생각 단계 : 각 단계 효과적으로 순차적있는 것은 귀하의 요구 사항 인 경우

myObject.updateDB(payload) 
    .thenCompose(__ -> getUserID(payload.ID())) 
    .thenAccept(id -> { 
     updateSomething(getProfile(id).join()); 
     notifyUser(id); 
    }) 
    .thenRun(() -> doSomething()) 
    .exceptionally(t -> doSomethingElse()); 

, 당신은 간단하게 사용할 수 있습니다 join :

전체 체인이 효율적으로 순차적 인 점을 감안하면
myObject.updateDB(payload) 
    .thenCompose(__ -> getUserID(payload.ID())) 
    .thenAccept(id -> { 
     updateSomething(getProfile(id).join()).join(); 
     notifyUser(id).join(); 
    }) 
    .thenRun(() -> doSomething()) 
    .exceptionally(t -> doSomethingElse()); 

, 당신은 똑바로 앞으로 쓸 수 있습니다 : 간단한 해결책이 아니다

myObject.updateDB(payload) 
    .thenRun(() -> { 
     YourUserIDType id = getUserID(payload.ID()).join(); 
     updateSomething(getProfile(id).join()).join(); 
     notifyUser(id).join(); 
     doSomething(); 
    }) 
    .exceptionally(t -> doSomethingElse()); 
관련 문제