Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dagger2 and Android Lifecycle with Kotlin

Dagger2 and Android Lifecycle with Kotlin

Takuji Nishibayashi

April 26, 2016
Tweet

More Decks by Takuji Nishibayashi

Other Decks in Technology

Transcript

  1. Lifecycle provider interface ActivityLifecycle { fun onCreate(savedInstanceStete: Bundle?) {} fun

    onSaveInstanceState(outState: Bundle?) {} fun onDestroy() {} //... }
  2. Lifecycle provider object Lifecycles { fun activity(vararg lifecycles: ActivityLifecycle): ActivityLifecycle

    { return object : ActivityLifecycle { override fun onCreate(savedInstanceStete: Bundle?) { lifecycles.forEach { it.onCreate(savedInstanceStete = savedInstanceStete) } } override fun onStart() { lifecycles.forEach { it.onStart() } } //... } }
  3. Provide Lifecycle provider @Module class UserModule() { @Provides @PerActivity fun

    lifecycle(presenter: UserPresenter) : ActivityLifecycle { return presenter //or return Lifecycles.activity(presenter, some, lifecycle, objects) } }
  4. Use lifecycle provider class UserActivity : AppCompatActivity() { @Inject lateinit

    var lifecycle : ActivityLifecycle var component : UserComponent by Delegates.notNull() override fun onCreate(savedInstanceState: Bundle?) { lifecycle.onCreate(savedInstanceStete = savedInstanceState) } override fun onDestroy() { lifecycle.onDestroy() } }
  5. Retain fragment class UserComponentFragment : Fragment() { var component: UserComponent?

    = null init { retainInstance = true } companion object { val TAG = "UserComponentFragment" } }
  6. Use retain fragment class UserActivity : AppCompatActivity() { override fun

    onCreate(savedInstanceState: Bundle?) { var storeFragment = supportFragmentManager .findFragmentByTag(UserComponentFragment.TAG) as? UserComponentFragment if (storeFragment == null) { storeFragment = UserComponentFragment() supportFragmentManager .beginTransaction() .add(storeFragment, UserComponentFragment.TAG) .commit() } if (storeFragment.component == null) { //init component } storeFragment.component.inject(this) } }