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

  • DiscoveryEach class is scanned at compile time and information for all marked classes is passed throughASMRegistered toDiscoveriesIn the class.
  • Compared with theARouterThe service discovery capabilities of routing frameworks,DiscoveryMajor functionality works at compile time and is not scanned at run timedex, has better performance.
  • Compared with theServiceLoader.DiscoverySupport for abstract classes, and access to implementation classesclassObject that can be adapted to richer frameworks.

Open source address

Github.com/xiazunyang/…

The installation

Current Version:

  1. 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
  2. Add the following code to the build.gradle file of the business module:

    api("cn.numeron:discovery.library:latest_version")
    Copy the code
  3. 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

  1. Create an interface in the base module and tag itDiscoverableComments:
@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

function