簡體   English   中英

從 Mono 調用返回一個值

[英]Return a value from a Mono call

Newbie to reactive programming in JAVA, I have a function buildRow that makes an async call to get hold of id and then use that determine a boolean value, this function always return's before async call gets completed. 我如何使它僅在異步調用完成並確定 boolean 值后返回?

public Row buildRow(Row row) {
    Mono<Long> id = reader.getColumn(row.getId());
    id
        .doOnNext(value-> {
            boolean isEnabled = reader.isEnabled(value);
            // This is getting returned second
            testRow(row, isEnabled);
         })
         .subscribe();
    // This is getting returned first
    return row;
}

public Row testRow(Row row, boolean isEnabled) {
  if (isEnabled) {
     return row;
  } else {
    return new Row();
  }
}

// Triggered in another function like this
map(row -> buildRow(row))

您可以將邏輯切換到該邏輯:

public Mono<Row> buildRow(Row row) {
    return reader.getColumn(row.getId())
            .map(reader::isEnabled)
            .filter(isEnabled -> isEnabled)
            .map(enabled -> row)
            .switchIfEmpty(Mono.just(new Row()));
}

之后,您可以從以下位置更改 buildRow 方法的調用:

map(row -> buildRow(row))

至:

flatMap(row -> buildRow(row))

否則,在閱讀器邏輯中將反應式與非反應式方法混合是沒有意義的。 你混合得越多,你遇到的問題就越多。

Mono是一個專門的Publisher者,它只能包含零個或一個事件。
Mono<T> Class 中,有block()方法:

public T block()

訂閱此 Mono 並無限期阻止,直到收到下一個信號。 如果 Mono 為空,則返回該值或 null。 如果出現 Mono 錯誤,則會引發原始異常(如果是已檢查異常,則將其包裝在 RuntimeException 中)。

綜上所述, block()方法用於獲取T類型的值。 現在,您可以使用block()方法返回您的Row類型值。

代碼如下:

public Row buildRow(Row row) {
    Mono<Long> id = reader.getColumn(row.getId());
    Row row = id.map(value-> {
            boolean isEnabled = reader.isEnabled(value);
            // use map return value
            return testRow(row, isEnabled);
         })
         .block();  // use block to compute and then get value
    // Now what you want could return
    return row;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM