How to implement Callback mechanism ( With Two Callbacks – No parameter )

This is all about “how to implement” callback mechanism in Core Java with one interface and more callback methods.
Steps to implement it
  1. Interface Class: One interface has to be created. This interface reference will be passed from UI class to background class. This will have two callback methods defined.
  2. Background Operation Class: One class for doing background operation. Which will accept interface reference as parameter. One different conditions this class will notify UI class.
  3. Calling Class: One class which can call background operation and implement interface class. This class will pass interface reference to background operation class.

CallbackInterface .java

This interface will just play a role of callback. We have two callback which will be invoked at two different scenarios. This interface will be passed from UI class to background class. 


package technical.jungle.com.callback;

/*
 * This interface will just play a role of callback. We have 
 * two callback which will be invoked at two different scenarios.
 */

public interface CallbackInterface {
void notifyInbetween();

void success();
}

CallbackWorkerDemo.java : For background operation


This callback class will accept reference of interface  “CallbackInterface”. Once some condition met then notify by first callback and once background work is being performed completely then inform(notify) it back to calling class.


package technical.jungle.com.callback;

public class CallbackDemo {
static CallbackInterface mCallbackInterface = new CallbackInterface() {

// Here notification/callback will be received from background
// operation.

@Override
public void notifyInbetween() {
// callback one
System.out.println(“notifyInbetween”);

}

@Override
public void success() {
// callback two
System.out.println(“success. Code completed.”);
}
};

public static void main(String args[]) {

CallbackWorkerDemo callbackWorkerThread = new CallbackWorkerDemo(
mCallbackInterface);
}
}

CallbackDemo.java

This class will responsible to do some background operation. This class will accept accept interface reference and once background operation is performed then notify back to main class. This callback class will accept reference of interface “CallbackInterface” and notify back to calling class.


package technical.jungle.com.callback;

public class CallbackWorkerDemo {

public CallbackWorkerDemo(CallbackInterface mCallbackInterface) {
// background operation.

for (int i = 0; i < 10; i++) {
// if some condition met, then notify by one callback.
if (i == 5) {
mCallbackInterface.notifyInbetween();
}
}
// Once all success then success callback.
mCallbackInterface.success();
}
}

Output


notifyInbetween

success. Code completed.

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

Your email address will not be published. Required fields are marked *