Orkun
Orkun

Reputation: 7228

How to wrap a function with andThen or similar in Java functional interface

I have some repetitive code:

router.post("/fleets/:fleetid/vehicles/:boxid/ping").handler(ctx -> pingBox(pingBoxTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/wakeup").handler(ctx -> wakeUp(wakeupTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/passthrough").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/expert").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/door").handler(ctx -> door(doorTimer, oemUrl, ctx));

In the handler of these methods, I:

  1. Start a timer
  2. Do some stuff
  3. Stop the timer

E.g.:

private void pingBox(Timer timer, String someArgs, RoutingContext ctx) {
    log.debug("ping request");
    
    Timer.Context timerCtx = timer.time();
    ctx.put("timer", timerCtx);

    ctx.response().headers().add("content-type", "text/plain");
    ctx.response().end("pong");

    timerCtx.stop();
}

How can I wrap the handler to avoid repeating code?

I've tried the following so far:

private void handleWithTimer(Timer timer, String url, RoutingContext ctx, BiConsumer<String, RoutingContext> handler){

    log.debug("saving timer");
    Timer.Context timerCtx = timer.time();
    ctx.put("timer", timerCtx);

    handler.accept(url, ctx);

    timerCtx.stop();
}

but the result is not very readable:

.. .handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, (s, c) -> pingBox(oemUrl, ctx)));

There must be a more concise way. Any ideas?

Upvotes: 4

Views: 696

Answers (1)

Philipp Hemmelmayr
Philipp Hemmelmayr

Reputation: 149

You can make your wrapping function more readable like this:

.handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, this::pingBox));

(of course only after adjusting your input parameters of pingBox, which it seems like you already did)

Upvotes: 4

Related Questions