- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在研究 Dagger2 + MVP 并在 Kotlin 上进行。我在理解 Dagger2 或 MVP 或它们的组合时遇到问题。
应用程序的构造和它应该如何工作的想法非常简单。该应用程序包含带有左侧导航的 MenuActivity
和几个 Fragments
(比方说 3),它们应该在 的
。 FrameLayout
中更改activity_menu.xml
我已经阅读了几篇文章并且已经花了几天时间研究 Dagger2。我将本文用作构建示例的教程:https://proandroiddev.com/dagger-2-part-ii-custom-scopes-component-dependencies-subcomponents-697c1fa1cfc
在我看来,Dagger 架构应该由三个 @Component
组成:(1) AppComponent,(2) MenuActivityComponent 和 (3) AccountFragmentComponent。根据我的理解和文章中的架构图,我的架构可以是这样的:(3) 取决于 -> (2) 取决于 -> (1)
每个 @Component
都有一个 @Module
:(1) AppModule,(2) MenuActivityModule 和 (3) AccountFragmentModule。对于 MVP 依赖关系的更清晰的方式,据我所知,(2) MenuActivityModule 和 (3) AccountFragmentModule 都应该 @Provide
Presenter
来自 MVP ideology 的 @Inject
在 MenuActivity
和其他 Fragment
中,例如 AccountFragment
。
应用模块
@Module
class AppModule(val app : App){
@Provides @Singleton
fun provideApp() = app
}
应用组件
@Singleton @Component(modules = arrayOf(AppModule::class))
interface AppComponent{
fun inject(app : App)
fun plus(menuActivityModule: MenuActivityModule): MenuActivityComponent
}
菜单 Activity 模块
@Module
class MenuActivityModule(val activity : MenuActivity) {
@Provides
@ActivityScope
fun provideMenuActivityPresenter() =
MenuActivityPresenter(activity)
@Provides
fun provideActivity() = activity
}
菜单 Activity 组件
@ActivityScope
@Subcomponent(modules = arrayOf(MenuActivityModule::class))
interface MenuActivityComponent {
fun inject(activity: MenuActivity)
fun plus(accountsModule : AccountsFragmentModule) : AccountsFragmentComponent
}
AccountsFragmentModule
@Module
class AccountsFragmentModule(val fragment: AccountsFragment){
@FragmentScope
@Provides
fun provideAccountsFragmentPresenter() =
AccountsFragmentPresenter(fragment)
}
AccountsFragmentComponent
@FragmentScope
@Subcomponent(modules = arrayOf(AccountsFragmentModule::class))
interface AccountsFragmentComponent {
fun inject(fragment: AccountsFragment)
}
我还有两个 @Scope
:ActivityScope 和 FragmentScope,据我所知,这将保证在应用程序中需要每个组件时只存在一个组件。
Activity 范围
@Scope
annotation class ActivityScope
fragment 作用域
@Scope
annotation class FragmentScope
在 Application 类中,我创建了一个 @Singleton
依赖关系图。
class App : Application(){
val component : AppComponent by lazy {
DaggerAppComponent
.builder()
.appModule(AppModule(this))
.build()
}
companion object {
lateinit var instance : App
private set
}
override fun onCreate() {
super.onCreate()
component.inject(this)
}
}
在 MenuActivity 中:
class MenuActivity: AppCompatActivity()
@Inject lateinit var presenter : MenuActivityPresenter
val Activity.app : App
get() = application as App
val component by lazy {
app.component.plus(MenuActivityModule(this))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
/* setup dependency injection */
component.inject(this)
/* setup UI */
setupMenu()
presenter.init()
}
private fun setupMenu(){
navigationView.setNavigationItemSelectedListener({
menuItem: MenuItem -> selectDrawerItem(menuItem)
true
})
/* Hamburger icon for left-side menu */
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
drawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(drawerToggle as ActionBarDrawerToggle)
}
private fun selectDrawerItem(menuItem: MenuItem){
presenter.menuItemSelected(menuItem)
// Highlight the selected item has been done by NavigationView
menuItem.isChecked = true
// Set action bar title
title = menuItem.title
// Close the navigation drawer
drawerLayout.closeDrawers()
}
@SuppressLint("CommitTransaction")
override fun showFragment(fragment: Fragment, isReplace: Boolean,
backStackTag: String?, isEnabled: Boolean)
{
/* Defining fragment transaction */
with(supportFragmentManager.beginTransaction()){
/* Select if to replace or add a fragment */
if(isReplace)
replace(R.id.frameLayoutContent, fragment, backStackTag)
else
add(R.id.frameLayoutContent, fragment)
backStackTag?.let { this.addToBackStack(it) }
commit()
}
enableDrawer(isEnabled)
}
private fun enableDrawer(isEnabled: Boolean) {
drawerLayout.setDrawerLockMode(if(isEnabled) DrawerLayout.LOCK_MODE_UNLOCKED
else DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
drawerToggle?.onDrawerStateChanged(if(isEnabled) DrawerLayout.LOCK_MODE_UNLOCKED
else DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
drawerToggle?.isDrawerIndicatorEnabled = isEnabled
drawerToggle?.syncState()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (drawerToggle!!.onOptionsItemSelected(item)) {
return true
}
return super.onOptionsItemSelected(item)
}
override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onPostCreate(savedInstanceState, persistentState)
drawerToggle?.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
drawerToggle?.onConfigurationChanged(newConfig)
}
}
MainActivityPresenter
class MenuActivityPresenter(val menuActivity: MenuActivity){
fun init(){
menuActivity.showFragment(AccountsFragment.newInstance(), isReplace = false)
}
fun menuItemSelected(menuItem: MenuItem){
val fragment = when(menuItem.itemId){
R.id.nav_accounts_fragment -> {
AccountsFragment.newInstance()
}
R.id.nav_income_fragment -> {
IncomeFragment.newInstance()
}
R.id.nav_settings -> {
IncomeFragment.newInstance()
}
R.id.nav_feedback -> {
OutcomeFragment.newInstance()
}
else -> {
IncomeFragment.newInstance()
}
}
menuActivity.showFragment(fragment)
}
}
activity_menu.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="@+id/frameLayoutContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="@+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
app:menu="@menu/main_menu"
app:headerLayout="@layout/nav_header"
/>
</android.support.v4.widget.DrawerLayout>
还有我理解中出现断点的地方:
class AccountsFragment : Fragment() {
companion object {
fun newInstance() = AccountsFragment()
}
val Activity.app : App
get() = application as App
val component by lazy {
app.component
.plus(MenuActivityModule(activity as MenuActivity))
.plus(AccountsFragmentModule(this))
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_accounts, container, false)
setHasOptionsMenu(true)
component.inject(this)
return view
}
}
我对 component
值的最后一部分有误解。我遇到了这样的情况,我需要 plus
MenuActivityComponent 的子组件并将其作为构造函数变量 MenuActivity 提供,但我知道这是错误的,即使我想要该实例也无法创建另一个实例申请中应该只有一个。
问题:我哪里错了?在我的代码中,在架构中,在对依赖注入(inject)的理解中,还是在这三者中?感谢您的帮助!
最佳答案
Also I have two @Scopes: ActivityScope and FragmentScope, so as I understand that will guarantee the existence of only one Component for the time every component is need in the application
Dagger 的瞄准镜不是什么神奇的仙尘,它可以为你管理生命周期。作用域的使用只是验证辅助,它可以帮助您不混合具有不同生命周期的依赖项。您仍然必须自己管理组件和模块对象,将正确的参数传递给它们的构造函数。由不同组件实例管理的依赖关系图是独立的并绑定(bind)到它们的 @Component 对象。请注意,我在某种意义上说“绑定(bind)”,它们是由它们创建的(通过构造函数),并且可以选择存储在它们内部,绝对没有其他魔法在幕后工作。因此,如果您需要在应用程序的各个部分之间共享一堆依赖项,您可能需要传递一些组件和模块实例。
在 fragment 的情况下,存在具有复杂生命周期的强依赖性——Activity。您在 onAttach
期间收到该依赖项,并在 onDetach
期间丢失它。因此,如果您真的想将一些依赖于 Activity 的东西传递给 Fragment,则必须传递那些依赖于 Activity 的组件/模块,就像在没有 MVP 的情况下传递 Activity 实例一样。
同样,如果您的 Activity 通过 Intent 接收到一些依赖项,您将必须从中反序列化该依赖项,并根据 Intent 内容创建一个模块......
Activity 和 Fragment 生命周期的复杂性加剧了使用 Dagger 注入(inject)时经常遇到的问题。 Android 框架是基于这样的假设构建的,即 Activity 和 Fragments 以序列化形式接收它们的所有依赖项。最后,一个写得很好的应用程序不应该在模块之间有太多的依赖关系(查找“紧耦合”)。由于这些原因,如果您不遵循严格的单一 Activity 范式,那么在您的项目中在本地化 Activity/Fagment 范围上使用 Dagger 可能根本不值得。许多人仍然这样做,即使这不值得,但 IMO,这只是个人喜好的问题。
关于android - Dagger2 + Kotlin 上的 MVP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723230/
Dagger 和 Dagger 2.0 有什么区别,为什么 Google 决定 fork 现有项目? 最佳答案 来自 Dagger 2 presentation 的一些引述 Dagger 1 的问题:
我想制作一个包含一个主要 Activity 和多个 fragment 的简单项目。在这里,我在一项 Activity 中有两个 fragment ,我想将演示者注入(inject)登录 fragmen
我是 dagger 的新手,我正在寻找如何在 dagger-2.x 中实现 spring 配置文件等功能。我想为我的开发环境和生产环境使用不同的 bean,但我使用的是带有 Java 的 Dagger
假设我有两个服务 AService 和 BService,它们都需要一个 API key 。 所以在我的模块中,我不能做类似的事情: @Provides @Singleton @A @ApiKey S
我对 Dagger 很陌生——我什至不知道它是否适用于我的应用程序 我有一个搜索页面,它返回有关给定名人的最新消息。 我写了一个测试来验证当我们搜索一个受欢迎的名人时结果会出现在页面上。 page有一
我最近将 dagger 2.8 更新为 2.9 dagger。和最新版本的文档已添加如下: -添加@BindsInstance组件构建器可以轻松绑定(bind)在图之外构建的实例。 -制作人:已添加
Dagger documentation页面说: To get the most out of compile-time validation, create a module that includ
我可以知道之间的区别吗? @Singleton VS 静态 在dagger2中提供? @Provides static User currentUser(AuthManager authManager
我有一个功能,我需要为不同的用户提供不同的房间数据库。 我正在使用 Dagger 2 创建房间数据库。我的应用程序组件创建一个房间数据库。当用户切换到另一个用户时,我想为此创建新的房间数据库,我需要创
我是 Dagger 2 的新手,正在尝试 IntelliJ 中的 Dagger 2 Coffee Example,它似乎不会生成 DaggerCoffeeApp_Coffee(它应该生成它),即使我密
我正在尝试在 Android 上使用 Dagger 2。我以前让它工作,我有一个 appModule 将依赖项注入(inject)应用程序中的特定类。我的问题是我收到错误 Error:(14, 55)
我是 kotlin 和 Dagger 的新手。我有一个小问题,我不知道如何解决,也没有找到解决方案。 这就是我所拥有的: @Module class AppModule (app: Applicati
我正在尝试使用 Dagger 建立一个项目。现在,当我构建时,没有为组件生成任何 Dagger* 类,并且出现以下错误: Error:(10, 8) error: [com.redditapp.dag
在 Dagger 中,我有时会看到有些组件只扩展一个接口(interface),而其他组件则使用 dependencies。 例如我们有一个基础组件: @Singleton @Component(mo
有没有办法告诉 Dagger 2 如何提供一些东西,但不允许它被注入(inject)? 假设我要注入(inject)一个 Qux .一个 Qux需要 Foo和 Bar : @Provides @Sin
( x-post from /r/androiddev ) 我只想在序言中说这不是一篇“哪个更好”的帖子;这严格来说是一个关于如何使用 Dagger 构建某些东西的问题(以及如何在 Kodein 中构
https://developer.android.com/topic/libraries/architecture/ 在Android架构蓝图中,为什么dagger是基于mvp架构而不是MVVM架构
我第一次开始同时使用 Kotlin 和 Dagger 2。我假设一切都与 Java 中的相同,但显然不完全相同。 Dagger 不会为我生成 Dagger* 文件。这是我的代码: 组件: @PerAc
我正在尝试将 Dagger 2 与 eclipse 集成,我使用的库如下: dagger-2.0.jar dagger-compiler-2.0.jar guava-13.0.1.jar javawr
我想练习这个Dagger 2 Vehicle Motor例子。 除了我的 gradel.build 之外,我所做的一切都与该教程中的一样: compile 'com.google.dagger:dag
我是一名优秀的程序员,十分优秀!