2017-07-28 1 views
0

私はモノのマップ機能内のデータを変換したい:長い実行タスクを持つモノをマップの中に戻すにはどうすればいいですか?

long result = 0.0; 

return Mono.just(result).map(value -> { 
    // do some long running transformation here 
    // and assign it to result (maybe 5 seconds task) 
    // in our case a request: 

    Mono<Result> resultObject = service.getResult(); 

    resultObject.subscribe(new Subscriber<Result>() { 
     @Override 
     public void onSubscribe(Subscription s) { 
      System.out.println("subscribe: " + System.currentTimeMillis()); 

      s.request(1); 
     } 

     @Override 
     public void onNext(Result result) { 
      System.out.println("on next: " + System.currentTimeMillis()); 

      value = result.getValue(); // this is not 0.0 
     } 

     @Override 
     public void onError(Throwable t) { 
      System.out.println("error " + t); 
     } 

     @Override 
     public void onComplete() { 
      System.out.println("complete"); 
     } 
    }); 

    return value; 
}); 

私はこれを呼び出した場合、マップ機能が実行される前に、それが戻っているので、私は常に、結果として0.0を取得します。私にとってはそれほど意味がない。返す前に私の結果を変えるにはどうしたらいいですか?

final CountDownLatch latch = new CountDownLatch(1); 
long result = 0.0; 

return Mono.just(result).map(value -> { 
    // do some long running transformation here 
    // and assign it to result (maybe 5 seconds task) 
    // in our case a request: 

    Mono<Result> resultObject = service.getResult(); 

    resultObject.subscribe(new Subscriber<Result>() { 
     @Override 
     public void onSubscribe(Subscription s) { 
      System.out.println("subscribe: " + System.currentTimeMillis()); 

      s.request(1); 
     } 

     @Override 
     public void onNext(Result result) { 
      System.out.println("on next: " + System.currentTimeMillis()); 

      value = result.getValue(); // this is not 0.0 

      latch.countDown(); 
     } 

     @Override 
     public void onError(Throwable t) { 
      System.out.println("error " + t); 
     } 

     @Override 
     public void onComplete() { 
      System.out.println("complete"); 
     } 
    }); 

    try { 
     latch.await(); 

     return value; 
    } catch(InterruptedException e) { 
     e.printStackTrace(); 

     return -1.0; 
    } 
}); 

答えて

1

正確flatMapが何のためにあるのかのように聞こえる:あなたの実行時間の長いタスクが非同期である場合、私は次のことを行うことができますが、私の意見では、これが最適解ではない

EDIT

Publisher<T>として表すことができ、それはflatMapによって非同期にトリガされます。

Mono#flatMap(Function)3.0.xMono#then(Function)と記載されています。 3.0.7中のSO

Mono.just(param).then(p -> service.getResult(p)); 

そして3.1.0.M3中:あなたが値を使用しない場合(サービスがパラメータを持っていないことを

Mono.just(param).flatMap(p -> service.getResult(p)); 

注意)あなたはおそらく、単純3.0.xのと3.1.xの両方に有効ですthen(Mono)()を使用して、継続Monoを提供することができます。

Mono.just(paramThatGetsIgnored).then(service.getResult()); 
を210

(この場合、開始点はMono.just(...)であまり関係ありません)

+0

3.0.xの 'then'から3.1.0の' flatMap'へ移行するための最良の戦略は、 'Mono .flatMap'を 'Mono.flatMapMany'と組み合わせて、次に' Mono.then(Function) 'を' Mono.flatMap(Function) 'と組み合わせて使用​​します。単一の「関数」を持たない他のすべての「その次の」バリアントは同じままです。 –

関連する問題