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

簡単高速なDIライブラリToothpick

zaki50
January 26, 2018

 簡単高速なDIライブラリToothpick

zaki50

January 26, 2018
Tweet

More Decks by zaki50

Other Decks in Technology

Transcript

  1. Ϟδϡʔϧఆٛ ApplicationModule.kt class ApplicationModule(private val application: Application) : Module() {

    init { bind() } private fun bind() { val repository = ModelRepository(application) bind(ModelRepository::class.java).toInstance(repository) bind(Foo::class.java).to(FooImpl::class.java) bind(Bar::class.java).toProvider(BarProvider::class.java) } }
  2. ࣮૷Ϋϥε FooImpl.kt class FooImpl @Inject constructor() : Foo { init

    { ... } } BarProvider.kt class BarProvider : Provider<Bar> { override fun get(): Bar = BarImpl() }
  3. ɹείʔϓͷ࡞Γํ MainActivity.kt class MyApplication : Application() { override fun onCreate()

    { super.onCreate() val scope = Toothpick.openScope(this) scope.installModules(ApplicationModule(this)) } override fun onTerminate() { super.onTerminate() Toothpick.closeScope(this) } }
  4. ɹωετͨ͠είʔϓ MainActivity.kt class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState:

    Bundle?) { super.onCreate(savedInstanceState) val scope = Toothpick.openScopes(application, this) scope.installModules(MainActivityModule(this)) } override fun onDestroy() { super.onDestroy() Toothpick.closeScope(this) } }
  5. ɹগ͠ݡ͍είʔϓ MainActivity.kt class MainActivity : AppCompatActivity() { private lateinit var

    activityId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ... activityId = getActivityId(savedInstanceState) scope = Toothpick.openScopes(application, activityId) } private fun getActivityId(savedInstanceState: Bundle?): String { return savedInstanceState?.getString("activity_id") ?: UUID.randomUUID().toString() } }
  6. ɹগ͠ݡ͍είʔϓ(ଓ͖) MainActivity.kt class MainActivity : AppCompatActivity() { ... override fun

    onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putString("activity_id", activityId) } override fun onDestroy() { super.onDestroy() if (isFinishing) { Toothpick.closeScope(activityId) } } }
  7. Ϟδϡʔϧ࢖༻ MyApplication.kt class MyApplication : Application() { override fun onCreate()

    { super.onCreate() val scope = Toothpick.openScope(this) scope.installModules(ApplicationModule(this)) } override fun onTerminate() { super.onTerminate() Toothpick.closeScope(this) } }
  8. ஫ೖ MainActivity.kt class MainActivity : AppCompatActivity() { @Inject lateinit var

    repo: ModelRepository @Inject lateinit var foo: Foo override fun onCreate() { super.onCreate() val scope = Toothpick.openScopes(application, this) scope.installModules(ApplicationModule(this)) Toothpick.inject(this, scope) } }