本文適合有必定的Dagger2使用基礎的同窗android
上一篇:dagger.android多模塊項目實現(一)
下一篇:Hilt多模塊項目實現(一)git
上一篇咱們講了dagger.android在普通多模塊項目中的用法
本篇咱們講下組件化基目怎麼使用dagger.androidgithub
咱們在Dagger2多模塊項目Component組織方式選擇(二)的基礎上改造實現segmentfault
具體實現和dagger.android多模塊項目實現(一)差很少,惟一差別是MultiModuleAndroidInjector放在BaseApplication中app
open class BaseApplication : Application(), HasAndroidInjector { val multiModuleAndroidInjector = MultiModuleAndroidInjector() lateinit var appComponent: AppComponent override fun onCreate() { super.onCreate() instance = this appComponent = DaggerAppComponent.factory().create(this) } companion object { lateinit var instance: BaseApplication } override fun androidInjector(): AndroidInjector<Any> { return multiModuleAndroidInjector } }
而後AppApplicationide
class AppApplication : BaseApplication() { override fun onCreate() { super.onCreate() //這部份應當各類模塊中初始化(後期用插件實現) val userDispatchingInjector = BaseDispatchingInjector() UserComponentHolder.userComponent.inject(userDispatchingInjector) multiModuleAndroidInjector.addInjector(userDispatchingInjector) val newsDispatchingInjector = BaseDispatchingInjector() NewsComponentHolder.newsComponent.inject(newsDispatchingInjector) multiModuleAndroidInjector.addInjector(newsDispatchingInjector) } }
這裏user,news模塊初始化放在app模塊中,與組件化思想不符,這裏能夠使用AppLike插件來實現,AppLike插件的做用是在任意模塊實現APP初動時作一些初始化工做。組件化
先中BaseApplication中加入AppLikeManager的onCreate和onTerminate方法this
open class BaseApplication : Application(), HasAndroidInjector { val multiModuleAndroidInjector = MultiModuleAndroidInjector() lateinit var appComponent: AppComponent override fun onCreate() { super.onCreate() instance = this appComponent = DaggerAppComponent.factory().create(this) AppLikeManager.onCreate(this) } override fun onTerminate() { AppLikeManager.onTerminate(this) super.onTerminate() } companion object { lateinit var instance: BaseApplication } override fun androidInjector(): AndroidInjector<Any> { return multiModuleAndroidInjector } }
而後每一個模塊建一個AppLike,把初始化代碼放在onCreate方法中spa
@AppLike class NewsAppLike : IAppLike { override fun onCreate(context: Context) { val newsDispatchingInjector = BaseDispatchingInjector() NewsComponentHolder.newsComponent.inject(newsDispatchingInjector) (context as? BaseApplication)?.run { multiModuleAndroidInjector.addInjector(newsDispatchingInjector) } } override fun getPriority(): Int { return 5 } override fun onTerminate(context: Context) { } } @AppLike class UserAppLike : IAppLike { override fun onCreate(context: Context) { val userDispatchingInjector = BaseDispatchingInjector() UserComponentHolder.userComponent.inject(userDispatchingInjector) (context as? BaseApplication)?.run { multiModuleAndroidInjector.addInjector( userDispatchingInjector ) } } override fun getPriority(): Int { return 5 } override fun onTerminate(context: Context) { } }
這樣APP啓動的時候每一個模塊的初始化都會自動執行了插件