gpt4 book ai didi

android - Dagger2 + Kotlin 上的 MVP

转载 作者:太空狗 更新时间:2023-10-29 16:27:46 31 4
gpt4 key购买 nike

我正在研究 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 的 @InjectMenuActivity 和其他 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com