10

CONTRUCTION

I have 2 modules:

  • app (application)
  • box (library module)

PROBLEM

I am trying to use part of app module from box module. The problem is that app module have dependency on box module therefore I cannot point from box module because that would create circular dependency.

How to get to app module methods from box module ?

Or

How to inform some receiver in app module that there is some data to get?

EDIT

I ended with 3rd module common that held intersection of module app and box.

JakubW
  • 1,101
  • 1
  • 20
  • 37
  • You might want to take some clues from here - http://stackoverflow.com/questions/6974696/starting-activity-from-android-library-project?rq=1 – random Sep 07 '15 at 12:46

2 Answers2

8

You can't call a module which is depending on your library directly. That kind of dependency would defeat the purpose of a library. But you can define an interface in your Box module, which clients of this library must implement to function propeprly.

Example: In your Box module define an interface

interface ThereIsSomeDataToGet(){
   void doSomething();
}

And in your app module, you may call

Box.registerCallback(new ThereIsSomeDataToGet(){...})

Now in the box module you have a callback to you application module, without any hard dependencies, and when the library you have some new data, you only need to call

ThereIsSomeDataToGet.doSomething();
Tamas
  • 221
  • 1
  • 8
  • What if activity restarted after Box.registerCallback(new ThereIsSomeDataToGet(){...}) and before ThereIsSomeDataToGet.doSomething();? – Exigente05 Jun 14 '17 at 09:38
2

Further elaborating on Tom's answer, here's a fully working solution:

In your Box module:

public interface Callback {
    void doSomething();
}

private static Callback callback;

public static void setCallback(Callback callback) {
    Box.callback = callback;
}

In your App module:

Box.setCallback(new Box.Callback() {
    @Override
    public void doSomething() {
        // Code from App module you want to run in Box module
    }
});

Finally, just call doSomething() from your Box module:

callback.doSomething();
S01ds
  • 301
  • 5
  • 8
  • What is this Box when it comes to a real code, I can get that its a module but how can I use in code, an example will be great – arun Jun 20 '23 at 07:52
  • It’s just a random name for a module, could be doing anything. I’m referring to the question where it’s called Box. – S01ds Jun 21 '23 at 08:10