aQuu
aQuu

Reputation: 565

Java simple callback

It is basic problem. I have class A which gives some task to class B. When class B finish the tast it must notify class A. I want register A class method as callback in class B.

I really want do it in this way, not by observer pattern with interface Observable.

public class A
{
    public void A()
    { 
        B b = new B()
        b.registerCallback(callback);
    }

    private void callback()
    {

    }

}

public class B
{
    private ???? callbackoNotify;

    public class registerCallback(??? callback)
    {
        callbackoNotify = callback;
    }

    public void notify()
    { 
        callback();
    }
}

Upvotes: 1

Views: 9765

Answers (2)

john16384
john16384

Reputation: 8044

You can do this without callbacks as well. Here's an example:

A a = ...
B b = ...

Let's say b has a doTask method like this:

public void doTask(Runnable task);

A can now call it like this:

b.doTask(() -> {System.out.println("Hi There");});

However, A will not be informed when the task gets completed. You could simply change the task like this:

Runnable taskForB = () -> {System.out.println("Hi There");};
Runnable wrapperForTaskWithCallback = () -> {
    taskForB.run();
    taskWasFinished();
};

And then run the wrapper task instead:

b.doTask(wrapperForTaskWithCallback);

And give A a method:

public void taskWasFinished();

Upvotes: 3

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

You can define an interface for the callback.

interface Callback{
    void call();
}

Then, let class A implement it.

class A implements Callback{
    private B b;

    public A(){
        b = new B();
        b.registerCallback(this);
    }    

    // Implementation of the callback interface
    public void call(){

    }
}

Then, let class B to handle the callback.

public class B
{
    private Callback callbackoNotify;

    public class registerCallback(Callback callback)
    {
        callbackoNotify = callback;
    }

    public void notify()
    { 
        callbackNotify.call();
    }
}

But in the above scenario, callbackNotify can be null. Therefore, it is better if you can pass that callback in the constructor to B.

Hope you got the idea.

Upvotes: 4

Related Questions