I am quite new to Reactive programming and would like to convert a method that returns List<Stirng>
into a reactive stream approach
using Smallrye Mutiny
.
I tried creating Publisher etc but could not find the right example to proceed further. Can someone please provide some guidance or suggestion on this?
As provided below code, I have a method that will provide a list of random strings. Here I need to wait until all elements are being added to List before returning. I want to achieve the reactive stream approach where instead of waiting for all the elements to be added to the list I wish to return it as soon as generated.
I believe it's possible to achieve this using the SmallRye Mutiny
, can you please let me know how to achieve the same?
import org.apache.commons.lang.RandomStringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
System.out.println(addElements(5));
}
private static List<String> addElements(final int elementsCount) {
final List<String> returnList = new ArrayList<>();
IntStream.range(0, elementsCount).forEach(count -> {
returnList.add(RandomStringUtils.randomAlphanumeric(17).toUpperCase());
});
return returnList;
}
}
Here's one way:
public class Main {
public static void main(String[] args) {
List<String> list = addElements(5).await().indefinetely();
System.out.println(list);
}
private static Uni<List<String>> addElements(final int elementsCount) {
return Multi.createFrom()
.range( 0, elementCount )
.map( integer -> RandomStringUtils.randomAlphanumeric( 17 ).toUpperCase() )
.collect()
.asList();
}
}
For reference, on the official site there is a helpful Getting Started