General_Code
General_Code

Reputation: 249

How to compose two Flux<> Objects into one

I am kind of new to reactive programming to begin with. After attending some talks about reactor and spring 5.0 I wanted to try this programming model on my own.

I have an application which builds two Flux objects from different API's using WebClient. I want to compose this 2 objects into one and return it to the user.

The code example would look like this:

public class User {
  private String username;
  //getters and setters
}

public class Address {
  private String street;
  //getters and setters;
}

public class CompleteUser {
  private String username;
  private String address;
  //getters and setters
}

And now in my handler method:

final Flux<User> = WebClient.create()...;
final Flux<Address> = WebClient.create()...;
final Flux<CompleteUser> = //somehow compose this two types into one

What method from reactor API should I use to achieve this? I found some methods to compose objects like combineLatest however in this case I want to compose exactly first item of first Flux with first item of second Flux and etc.

Upvotes: 1

Views: 3942

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

Flux.zip static method is exactly what you are looking for. For combination of 2 sources, you can provide a BiFunction to produce the result.

Flux<CompleteUser> complete = Flux.zip(fluxUser, fluxAddress, (u, a) -> new CompleteUser(u, a));
//if the ctor perfectly matches, you can also use CompleteUser::new

Upvotes: 5

Related Questions