Skip to content

Remote callback

Brian S. O'Neill edited this page Dec 5, 2022 · 4 revisions

Implementing remote callbacks requires no special effort because of Dirmi's bidirectional design. Simply pass one or more remote objects to a remote method.

public interface WeatherService extends Remote {
    /**
     * Predict the weather and pass status to the listener.
     */
    void predict(Location loc, int days, PredictionListener listener) throws RemoteException;
}

public interface PredictionListener extends Remote {
    /**
     * Called during prediction to indicate how complete it is.
     * Return false if prediction should cease.
     */
    boolean progress(double amount) throws RemoteException;

    @Disposer
    void predictionComplete(WeatherReport report) throws RemoteException;
}

The client side might look like so:

    WeatherService service = ...
 
    class OurListener implements PredictionListener {
        volatile boolean shouldStop;
 
        @Override
        public boolean progress(double amount) {
            System.out.println("Prediction progress: " + amount);
            return !shouldStop;
        }
 
        @Override
        public void predictionComplete(WeatherReport report) {
            System.out.println("Weather report: " + report);
        }
    }
 
    OurListener listener = new OurListener();
    service.predict(loc, 7, listener);
    ...

And the server side might be:

    @Override
    public void predict(Location loc, int days, PredictionListener listener) {
        Predictor predictor = startPrediction(loc, days);
        try {
            while (true) {
                double progress = predictor.waitForProgress();
                if (progress >= 1.0) {
                    break;
                }
                if (!listener.progress(progress)) {
                    predictor.stopPrediction();
                    return;
                }
            }
            listener.predictionComplete(predictor.getReport());
        } catch (RemoteException e) {
            predictor.stopPrediction();
        } finally {
            Session.dispose(listener);
        }
    }
Clone this wiki locally