Discovery
By creating an interface (or abstract class) in a lower module and marking the @Discoverable annotation, and then creating an Implementation class in another upper module and marking the @Implementation annotation, it is possible to obtain instances of that interface or abstract class from the Discoveries class in any module in the project. Assists Android developers in accessing data between modules.
Principle and similar framework differences
Discovery
Each class is scanned at compile time and information for all marked classes is passed throughASM
Registered toDiscoveries
In the class.- Compared with the
ARouter
The service discovery capabilities of routing frameworks,Discovery
Major functionality works at compile time and is not scanned at run timedex
, has better performance. - Compared with the
ServiceLoader
.Discovery
Support for abstract classes, and access to implementation classesclass
Object that can be adapted to richer frameworks.
Open source address
Github.com/xiazunyang/…
The installation
Current Version:
-
Add the following code at the appropriate location in the root module’s build.gradle:
buildscript { repositories { ... mavenCentral() } dependencies { ... // Add the Discovery plug-in classpath("cn.numeron:discovery.plugin:latest_version")}}Copy the code
-
Add the following code to the build.gradle file of the business module:
api("cn.numeron:discovery.library:latest_version") Copy the code
-
Add the following code to the build.gradle file of the main module:
plugins { id("com.android.application")...// Apply the Discovery plugin id("discovery")}Copy the code
Example of sequential initialization for a multi-module project
- Create an interface in the base module and tag it
Discoverable
Comments:
@Discoverable
interface Initializer {
fun init(application: Application)
}
Copy the code
2. Create Initializer Implementation class in other modules that need to be initialized, mark Implementation annotation, and specify the value of order. The smaller the value of order, the higher the priority:
@implementation (order = 0) class AModuleInitializer: Initializer {override fun init(application: override fun init) Application) { //init a module } }Copy the code
@implementation (order = 10) class BModuleInitializer: Initializer {override fun init(application: Application) { //init b module } }Copy the code
3. Get all Initializer instances from the onCreate method of Application and iterate through them, calling init:
class MyApplication: Application() {override fun onCreate() {// Get all IInitiator implementations, And perform the init method val initializerList = Discoveries. GetAllInstances < IInitializer > () initializerList. ForEach {/ / order numerical implementation class priority call it.init(this) } } }Copy the code