Slide 1

Slide 1 text

How to use Dagger 2 in Android Marcelo Benites @marcelorbenites

Slide 2

Slide 2 text

About Me

Slide 3

Slide 3 text

Dependency Injection Dependency injection is a technique whereby one object supplies the dependencies of another object.

Slide 4

Slide 4 text

Dagger 1 or 2?

Slide 5

Slide 5 text

Dagger 2 ● Better performance. ● No reflection. ● First to implement the full stack with generated code. ● Easier to debug. ● Easy to use Proguard. ● Harder to replace dependencies for testing. ● Way more complex.

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Why Dagger? ● Eases DI in Android components (ContentProvider, Activity, Service, Application and BroadcastReceiver) ● Eases object's lifecycle management (Scopes). ● "Eases" the replacement of dependencies for Functional (UI) Testing. ● Standardizes object creation (large codebases/big teams).

Slide 8

Slide 8 text

Why NOT Dagger? ● Steep learning curve. ● Too many features you don't necessarily need. ● May cause performance problems (if misused). ● Easely leaks into all layers of your application. ● Hard to get rid of.

Slide 9

Slide 9 text

How to use Dagger?

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

How to use Dagger? ● dagger.android module? ● @Inject annotated constructor or @Provides annotated methods? ● How many components? ● How do I group my classes in modules? ● How do I use scopes? ● Multibinding? ● Producers? ● Subcomponents?

Slide 12

Slide 12 text

Dagger Android Pattern

Slide 13

Slide 13 text

Dagger Android Pattern ● Dagger solves - and only solves - Android components injection and lifecycle problems. ● Always @Produces in modules never @Inject in constructors (only for Android components dependencies). ● Application component. ● Activity component as Application subcomponent. ● Fragment component as Activity subcomponent. ● BaseActivity, BaseFragment and BaseApplication manage components lifecycle. ● Three scopes ApplicationScope, ActivityScope and FragmentScope. ● Modules based on your architecture.

Slide 14

Slide 14 text

Architecture

Slide 15

Slide 15 text

Architecture Android SDK Interactors Entities SQLite Retrofit Presenters Realm Dagger OkHttp Gateways

Slide 16

Slide 16 text

Contacts Application

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

@Scope @MustBeDocumented @kotlin.annotation.Retention(value = AnnotationRetention.RUNTIME) annotation class ApplicationScope

Slide 19

Slide 19 text

@ApplicationScope @Component(modules = [InteractorModule::class, GatewayModule::class]) interface ApplicationComponent

Slide 20

Slide 20 text

abstract class BaseApplication : Application() { lateinit var component: ApplicationComponent override fun onCreate() { super.onCreate() component = DaggerApplicationComponent .builder() .interactorModule(InteractorModule()) .gatewayModule(GatewayModule(this)) .build() } }

Slide 21

Slide 21 text

@Module class InteractorModule { @ApplicationScope @Provides fun provideContactsInteractor(contactsGateway: ContactsGateway): ContactsInteractor { return ContactsInteractor(contactsGateway) } }

Slide 22

Slide 22 text

@Module class GatewayModule(private val application: Application) { @ApplicationScope @Provides fun provideContactsGateway(): ContactsGateway { return ContentResolverContactsGateway(application.contentResolver) } }

Slide 23

Slide 23 text

class ContactsApplication: BaseApplication() { @Inject lateinit var contactsInteractor: ContactsInteractor override fun onCreate() { super.onCreate() component.inject(this) contactsInteractor.setup() } }

Slide 24

Slide 24 text

@ApplicationScope @Component(modules = [InteractorModule::class, GatewayModule::class]) interface ApplicationComponent { fun inject(contactsApplication: ContactsApplication) }

Slide 25

Slide 25 text

Contacts Presentation

Slide 26

Slide 26 text

Contacts Presentation ● ContactsActivity container. ● ContactListFragment - display list of contacts. ● ContactDetailFragment - display contact detail. ● MVP architecture. ● ContactsListPresenter ● ContactDetailPresenter

Slide 27

Slide 27 text

@Scope @MustBeDocumented @kotlin.annotation.Retention(value = AnnotationRetention.RUNTIME) annotation class ActivityScope

Slide 28

Slide 28 text

@ActivityScope @Subcomponent(modules = [NavigatorModule::class]) interface ActivityComponent

Slide 29

Slide 29 text

abstract class BaseActivity : AppCompatActivity() { lateinit var component: ActivityComponent private set override fun onCreate(savedInstanceState: Bundle?) { component = (application as BaseApplication).component.plus(NavigatorModule(this)) super.onCreate(savedInstanceState) } }

Slide 30

Slide 30 text

@ApplicationScope @Component(modules = [InteractorModule::class, GatewayModule::class]) interface ApplicationComponent { fun plus(navigatorModule: NavigatorModule) : ActivityComponent fun inject(contactsApplication: ContactsApplication) }

Slide 31

Slide 31 text

@Module class NavigatorModule(private val activity: AppCompatActivity) { @ActivityScope @Provides fun provideContactsNavigator(): ContactsNavigator { return FragmentManagerContactsNavigator(activity.supportFragmentManager!!, R.id.activity_contacts_container) } }

Slide 32

Slide 32 text

class ContactsActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_contacts) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.activity_contacts_container, ContactListFragment.create()) .commit() } } }

Slide 33

Slide 33 text

@Scope @MustBeDocumented @kotlin.annotation.Retention(value = AnnotationRetention.RUNTIME) annotation class FragmentScope

Slide 34

Slide 34 text

@FragmentScope @Subcomponent(modules = [PresenterModule::class]) interface FragmentComponent

Slide 35

Slide 35 text

abstract class BaseFragment : Fragment() { lateinit var component: FragmentComponent private set override fun onAttach(context: Context?) { component = (activity as BaseActivity).component.plus(PresenterModule(this)) super.onAttach(context) } }

Slide 36

Slide 36 text

@ActivityScope @Subcomponent(modules = [NavigatorModule::class]) interface ActivityComponent { fun plus(presenterModule: PresenterModule) : FragmentComponent }

Slide 37

Slide 37 text

@Module class PresenterModule { @FragmentScope @Provides fun provideContactListPresenter(contactsInteractor: ContactsInteractor, contactsNavigator: ContactsNavigator): ContactListPresenter { return ContactListPresenter(contactsInteractor, contactsNavigator) } @FragmentScope @Provides fun provideContactDetailPresenter(contactsInteractor: ContactsInteractor): ContactDetailPresenter { return ContactDetailPresenter(contactsInteractor) } }

Slide 38

Slide 38 text

class ContactListFragment: BaseFragment(), ContactListView { @Inject lateinit var presenter: ContactListPresenter override fun onAttach(context: Context?) { super.onAttach(context) component!!.inject(this) } override fun onResume() { super.onResume() presenter.attachView(this) } override fun onPause() { presenter.detachView() super.onPause() } …….. }

Slide 39

Slide 39 text

class ContactDetailFragment: BaseFragment(), ContactDetailView { @Inject lateinit var presenter: ContactDetailPresenter override fun onAttach(context: Context?) { super.onAttach(context) component!!.inject(this) } override fun onResume() { super.onResume() presenter.attachView(this) } override fun onPause() { presenter.detachView() super.onPause() } …... }

Slide 40

Slide 40 text

@FragmentScope @Subcomponent(modules = [PresenterModule::class]) interface FragmentComponent { fun inject(contactDetailFragment: ContactDetailFragment) fun inject(contactListFragment: ContactListFragment) }

Slide 41

Slide 41 text

Lifecycle ApplicationScope ActivityScope FragmentScope FragmentScope ContactsManager ContactsNavigator ContactDetail Presenter ContactList Presenter

Slide 42

Slide 42 text

Functional (UI) Testing

Slide 43

Slide 43 text

abstract class BaseApplication : Application() { lateinit var component: ApplicationComponent private set override fun onCreate() { super.onCreate() component = createComponent() } open fun createComponent(): ApplicationComponent { return DaggerApplicationComponent.builder() .interactorModule(InteractorModule()) .gatewayModule(GatewayModule(this)) .build() } }

Slide 44

Slide 44 text

@ApplicationScope @Component(modules = [TestGatewayModule::class, InteractorModule::class]) interface TestApplicationComponent: ApplicationComponent

Slide 45

Slide 45 text

class TestComponentApplication: ContactsApplication() { override fun createComponent(): ApplicationComponent { return DaggerTestApplicationComponent .builder() .interactorModule(InteractorModule()) .testGatewayModule(TestGatewayModule()) .build() } }

Slide 46

Slide 46 text

class TestComponentRunner: AndroidJUnitRunner() { override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application { return super.newApplication(cl, TestComponentApplication::class.java.name, context) } }

Slide 47

Slide 47 text

android { …... defaultConfig { testInstrumentationRunner "com.yourapplication.TestComponentRunner" } }

Slide 48

Slide 48 text

@Module class TestGatewayModule { @ApplicationScope @Provides fun provideContactsGateway(): ContactsGateway { return FakeContactsGateway() } }

Slide 49

Slide 49 text

class FakeContactsGateway: ContactsGateway { var fakeContacts: List = arrayListOf() override fun getContacts(): List { return fakeContacts } }

Slide 50

Slide 50 text

@RunWith(AndroidJUnit4::class) class ContactsActivityTest { @Rule @JvmField val rule: ActivityTestRule = ActivityTestRule(ContactsActivity::class.java) @Inject lateinit var contactsGateway: ContactsGateway @Test fun shouldShowContacts() { val testComponentApplication = InstrumentationRegistry.getTargetContext().applicationContext as TestComponentApplication (testComponentApplication.component as TestApplicationComponent).inject(this) (contactsGateway as FakeContactsGateway).fakeContacts = arrayListOf(Contact("Bob Marley", "+19999299299")) // Exercise the UI // Assert result } }

Slide 51

Slide 51 text

To inject or not to inject?

Slide 52

Slide 52 text

To inject or not to inject? ● To Inject ○ Interactors ○ Gateways ○ Presenters ● Not to Inject ○ View classes (RecyclerView.Adapter, LayoutManager, Views, etc...)

Slide 53

Slide 53 text

Questions?