Question

This is my situation in pseudocode:

function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            sendAllPlayersTheirCards()
        }
        return OK;
    }();

    sendResponse(response);

}

When players 1-3 connect, they get added to the list of players and OK is returned to them, at which point they will set stuff up on their side. When player 4 connects, however, before the response to his request is sent, all players are sent their cards. Because player 4 has not received a response to his request yet, he hasn't initialised correctly yet and errors upon receiving his cards.

What I'd like to have is this:

function onRequest() {
    receiveConnectionRequest();

    response = function onConnect() {
        playersConnected++;
        if (playersConnected == 4) {
            plan(sendAllPlayersTheirCards())
        }
        return OK;
    }();

    sendResponse(response);

    executePlanned() // now cards are sent
}

Is there a general pattern for that? The onConnect function is in a different class and should not be aware of the implementation details of onRequest.

I'm specifically trying to implement this in Java, but generic solutions are welcome.

Was it helpful?

Solution

Many good solutions to this, but I would suggest using a call back.

Don't think of it as doing something after the method returns, think of it as calling back to report a state or trigger an event.

Search for event pattern , or call backs in Java. Here is one link I found.

The delegation pattern is very similar to.

OTHER TIPS

Can you not send the response first and then do the "if(playersConnected" check after?

I'm not sure about this closure syntax you have here. Can you just have this instead?

function onRequest() {
    playersConnected++;

    sendResponse(OK);

    if (playersConnected == 4) {
        sendAllPlayersTheirCards()
    }
}

I could do it like this:

function onRequest(request) {

 game.handleRequest(request, function(response) {
  sendResponse(response);
 }

}

class game
function handleRequest(request, sendResponse:Function) {
 players++;
 sendResponse(OK);
 if (players == 4) sendCards();
}

This seems like a relevant tutorial:

Using Callable to Return Results From Runnables

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top