Flux in Spring Boot
Definition
A Flux is a core component of the Reactor library, which is part of the reactive programming model in Spring Boot. It represents an asynchronous sequence of 0 to N emitted items, which can be optionally terminated by an error or a completion signal. This makes Flux a powerful tool for handling streams of data in a non-blocking, reactive manner.
Creating and Using Flux
Flux can be created in various ways, as demonstrated in the following code snippet:
Flux<Integer> intFlux = Flux.just(1,2,3);
Flux<Integer> intFluxRange = Flux.range(1,10);
Flux<String> stringFlux = Flux.fromIterable(List.of("foo", "bar"));
Flux<String> anotherStringFlux = Flux.fromArray(new String[] {"foo", "bar"}); #1
Mono<Integer> emptyMono = Mono.empty();
Mono<Integer> intMono = Mono.just(1); #2
intFlux.map(i -> i * 2).subscribe(System.out::println); #3
- Creating Flux: You can create a Flux using static methods like
just,range,fromIterable, andfromArray. - Creating Mono: Mono is another reactive type that represents a single value or an empty value. It can be created using
Mono.empty()orMono.just(value). - Using Flux: The
mapfunction is used to transform each item emitted by the Flux. In this example, each integer is multiplied by 2 and printed to the console.
Transformations and Error Handling
Flux allows for user-defined transformations on the emitted items. Once a transformation is applied, the items are converted to another Flux. The lifecycle of a Flux, including its termination and error handling, is visually represented in the following figure:
Figure 8.8 The items emitted by the Flux undergo a user-defined transformation. Once the transformation is applied, the items are converted to another Flux. Once the Flux terminates (i.e., it stops producing items), it is represented by a vertical line. An error processing an item is represented with the X symbol.
Testing with Flux
Testing reactive streams can be done using tools like StepVerifier. The following example demonstrates how to test a request stream endpoint that returns a Flux of Course objects:
@Test
public void testRequestStream() {
Flux<Course> courseFlux = requester
.route("request-stream")
.data(new Course("Spring"))
.retrieveFlux(Course.class); #1
StepVerifier.create(courseFlux)
.consumeNextWith(course ->
➥ assertThat(course.getCourseName()).isEqualTo("Your course name: Spring.
➥ Response #0"))
.expectNextCount(0)
.consumeNextWith(course ->
➥ assertThat(course.getCourseName()).isEqualTo("Your course name: Spring.
➥ Response #1"))
.thenCancel()
.verify(); #2
}
- Requesting a Stream: A request is sent, expecting a stream of courses as a
Flux<Course>. - Verifying the Response:
StepVerifieris used to verify the response, checking the course names and then canceling the stream to stop further data retrieval.
Repository and Controller Integration
Flux is often used in repository interfaces and controllers to handle data operations and API endpoints. For example, the CourseRepository interface extends ReactiveCrudRepository and includes a method that returns a Flux of courses by category:
@Repository
public interface CourseRepository extends ReactiveCrudRepository<Course, Integer> {
Flux<Course> findByCategory(String category);
}
In a Spring controller, Flux can be used to define GraphQL endpoints, as shown in the following example:
@Controller
@RequiredArgsConstructor
public class GraphqlCourseController {
private final CourseRepository courseRepository;
private final ReviewRepository reviewRepository;
@QueryMapping
Flux<Course> courses() {
return this.courseRepository.findAll();
}
@QueryMapping
Flux<Review> reviews(@Argument Integer courseId) {
return this.reviewRepository.findByCourseId(courseId);
}
@QueryMapping
Flux<Course> coursesByCategory(@Argument String category) {
return this.courseRepository.findByCategory(category);
}
@MutationMapping
Mono<Course> addCourse(@Argument String name, @Argument String
➥ category, @Argument String description) {
return this.courseRepository.save(new Course(null, name, category,
➥ description));
}
@MutationMapping
Mono<Review> addReview(@Argument Integer courseId, @Argument String
➥ reviewerName, @Argument Integer rating, @Argument String comment) {
return this.reviewRepository.save(new Review(null, courseId,
➥ reviewerName, rating, comment));
}
}
This controller defines several query and mutation mappings, utilizing Flux to handle multiple data items and Mono for single data items.
FAQ (Frequently asked questions)
What is a Flux in Project Reactor?
How are items transformed in a Flux?
What does a vertical line represent in a Flux diagram?
What does the X symbol represent in a Flux diagram?
How can you create a Flux in Project Reactor?
How can you create a Mono in Project Reactor?
How do you use a Flux to perform operations on its items?
How do you test a RequestStream endpoint using Flux?
What is the purpose of StepVerifier in testing Flux?
What is the CourseRepository interface in a Spring Boot application?
How does the CourseRepository interface use Flux?