rayman
rayman

Reputation: 21606

How to compose Hystrix observables using java8 and rxjava

I got two api's to invoke. both them wrapped with Hystrix Observable:

here is one for example:

@HystrixCommand()
    public Observable<String> getAvailableFlightBookings() {
        return new ObservableResult<String>() {
            @Override
            public String invoke() {
                URI uri = registryService.getServiceUrl("flight-booking-service", "http://localhost:8081/flight-booking-service");
                String url = uri.toString() + "/flights/list";
                ResponseEntity<String> resultStr = restTemplate.getForEntity(url, String.class);
                return resultStr.getBody();
            }
        };
    }

I have the following code which I am struggling to complete:

public DeferredResult<FlightDetails> getAllFlightDetails() {
        //Calling previous defined functions
        Observable<String> availableFlightBookings=flightBookingIntegrationService.getAvailableFlightBookings();
        Observable<String> couponId=couponIntegrationService.getCoupon();


        Observable<String> details = Observable.zip(

    ..?


    }

I am not sure how to invoke the following API's:

flightBookingIntegrationService.getAvailableFlightBookings();
couponIntegrationService.getCoupon();

and populate the final result object (FlightDetails) using the Observable.zip

FlightDetails:

public class FlightDetails {

    String couponId;
    String availableFlightList;

..
}

Thank you, ray.

Upvotes: 1

Views: 1884

Answers (2)

Joao Evangelista
Joao Evangelista

Reputation: 2465

First make your Hystrix command class a @Component since you are using Spring, then just Autowire it into yout controller and call

And using lambdas, will look something like this:

public DeferredResult<FlightDetails> getAllFlightDetails() {

    Observable<String> availableFlightBookings=flightBookingIntegrationService.getAvailableFlightBookings();
    Observable<String> couponId=couponIntegrationService.getCoupon();

    //Create a new DeferredResult
    DeferredResult<FlightDetails> result = new DeferredResult();

    Observable.zip(availableFlightBookings,couponId, (avaliable, coupon) -> {
     // do some logic here or just..
    return new FlightDetails(avaliable,coupon);
    }).subscribe(result::setResult,result::setErrorResult);
    return result;
}

Upvotes: 1

Egor Neliuba
Egor Neliuba

Reputation: 15054

I'm not familiar with Hystrix, but zipping two observables shouldn't be different from pure RxJava.

Observable.zip(availableFlightBookings, couponId, new Func2<String, String, FlightDetails>() {
    @Override
    public FlightDetails call(String availableFlights, String coupon) {
        return new FlightDetails(availableFlights, coupon);
    }
}).subscribe();

Upvotes: 2

Related Questions