I have this code which is used to get a list from a reactive spring JPA repository:
Mono<List<ActivePairs>> list = activePairsService.findAllOrdered().collectList();
ActivePairs obj = new ActivePairs().pair("All");
I would like to add item at the beginning of the list:
I tried:
list.mergeWith(new ActivePairs().pair("All"));
But I get:
Required type: Publisher
<? extends java.util.List<io.domain.ActivePairs>>
Provided: ActivePairs
Do you know what is the proper way to implement this?
EDIT:
@Query(value = "SELECT ......")
Flux<ActivePairs> findAll();
Obj:
@Table("active_pairs")
public class ActivePairs implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Column("pair")
private String pair;
..... getter, setter, toString();
}
........
Mono<List<ActivePairs>> resultList = findAll().collectList();
resultList.subscribe(
addressList -> {
addressList.add(0,new ActivePairs().id(1111L).pair("All"));
},
error -> error.printStackTrace()
);
Using above code All
is not added into the list.
CodePudding user response:
You can use Mono.doOnNext()
to add to the inner list in transit:
list.doOnNext(list -> list.add(0, new ActivePairs().pair("All")))
Edit
Not sure why it doesn't work for you. Here is an example that shows the working concept:
Mono<List<String>> source = Flux.just("A", "B", "C").collectList();
source
.doOnNext(list -> list.add(0, "All"))
.subscribe(
System.out::println,
Throwable::printStackTrace,
() -> System.out.println("Done"));
prints:
[All, A, B, C]
Done
CodePudding user response:
Its impossible to modify List<ActivePairs>
from Mono<List<ActivePairs>>
. If the List isn't available yet since Mono
and Flux
are asynchronous/non-blocking by their nature, you can't get it except by waiting until it comes in and that's what blocking is.
You can subscribe to the Mono from the calling method and the Subscriber you pass will get the List when it becomes available. E.g
list.subscribe(
addressList -> {
adressList.add(0,new ActivePairs().pair("All"));
},
error -> error.printStackTrace(),
() -> Console.out.println("completed without a value")
)
NOTE :
There are also methods Mono::doOnSuccess
, and Mono::doOnNext
:
Mono::doOnSuccess
triggers when the Mono completes successfully - result is either T or null, which means the processing itself successfully finished regardless the state of data and is executed although the data are not available or present but the pipeline itself succeed.
Mono::doOnNext
triggers when the data is emitted successfully, which means the data is available and present.
To get list from Mono use block()
method, like this:
List<ActivePairs> pairs = list.block();
When you do System.out.println(pairs)
you should see item added in your list.