Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate between lib module and main module

Tags:

android

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.

like image 974
JakubW Avatar asked Sep 07 '15 12:09

JakubW


2 Answers

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();
like image 150
Tom Avatar answered Nov 24 '22 16:11

Tom


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();
like image 42
S01ds Avatar answered Nov 24 '22 17:11

S01ds