Share
Embed
Getting Big Payouts with Koin -- Droidcon NYC
Thanks to its clean design, Koin is quickly gaining popularity as a service locator framework. Highlights include its excellent documentation, accessible api, and the pure Kotlin source code.
In this talk, we’ll go over basic usage like factories, singles, and modules. We’ll talk about scoping and lazy-loading modules, and we’ll look at its integration with Android screens and ViewModels. Then, and most importantly, we’ll see how we can use Koin to quickly and easily generate mocked dependencies for clean and hermetic tests.
Rick Busarow
August 26, 2019
Transcript
111 slides
-
@rbusarow Screen ViewModel UserId Repository Dao Room Database App Context
Service Retrofit OkHttpClient Base Url -
@rbusarow class UserRepository { internal val service: UserService = retrofit.create<UserService>()
internal val dao: UserDao = database.userDao } Normal Control Flow -
@rbusarow class UserRepository { internal val okHttpClient: OkHttpClient = OkHttpClient()
internal val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://example.dev") .client(okHttpClient) .build() internal val database: Database = Database.init(APP_CONTEXT) internal val service: UserService = retrofit.create<UserService>() internal val dao: UserDao = database.userDao } Normal Control Flow -
@rbusarow class UserRepository { internal val okHttpClient: OkHttpClient = OkHttpClient()
internal val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://example.dev") .client(okHttpClient) .build() internal val database: Database = Database.init(APP_CONTEXT) internal val service: UserService = retrofit.create<UserService>() internal val dao: UserDao = database.userDao } Normal Control Flow -
@rbusarow Service Location Dependency Injection class UserViewModel { private val
repository = Locator.createRepository() } Inversion of Control -
@rbusarow Service Location Dependency Injection class UserViewModel { private val
repository = Locator.createRepository() } class UserViewModel(val repository: UserRepository) { lateinit var otherDependency : OtherDependency } Inversion of Control -
class UserScreen : Fragment() { lateinit var viewModel: UserViewModel override
fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } object Injector { fun inject(screen: UserScreen) { screen.viewModel = TODO() } } @rbusarow Field Injection -
class UserScreen : Fragment() { lateinit var viewModel: UserViewModel override
fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } object Injector { fun inject(screen: UserScreen) { screen.viewModel = TODO() } } @rbusarow Field Injection -
@rbusarow class UserScreen : Fragment() { lateinit var viewModel: UserViewModel
override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } object Injector { fun inject(screen: UserScreen) { screen.viewModel = TODO() } } Field Injection public mutable late init -
@rbusarow class UserRepository( private val service: UserService, private val dao:
UserDao ) { … } Constructor Injection -
@rbusarow class UserViewModel { val repository = UserRepository(service = TODO(),
dao = TODO()) } Constructor Injection -
@rbusarow class UserViewModel { val client = OkHttpClient() val retrofit
= Retrofit.Builder() .baseUrl("https://example.dev") .client(client) .build() val service = retrofit.create<UserService>() val database = Database.init(APP_CONTEXT) val dao = database.userDao val repository = UserRepository(service = service, dao = dao) } Constructor Injection -
@rbusarow class UserViewModel { val client = OkHttpClient() val retrofit
= Retrofit.Builder() .baseUrl("https://example.dev") .client(client) .build() val service = retrofit.create<UserService>() val database = Database.init(APP_CONTEXT) val dao = database.userDao val repository = UserRepository(service = service, dao = dao) } Constructor Injection -
@rbusarow class UserViewModel(service: UserService, dao: UserDao) { val repository =
UserRepository(service = service, dao = dao) } Constructor Injection -
@rbusarow class UserViewModel( private val repository: UserRepository ) : ViewModel()
Constructor Injection -
@rbusarow class UserScreen : Fragment() { val viewModel = UserViewModel(repository
= TODO()) } Constructor Injection -
@rbusarow class UserScreen : Fragment() { lateinit var viewModel :
UserViewModel override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Field Injection… -
@rbusarow class UserScreen : Fragment() { lateinit var viewModel :
UserViewModel override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Field Injection… -
@rbusarow class UserScreen : Fragment() { private val viewModel by
lazy { ViewModelProviders .of(this) .get(UserViewModel::class.java) } override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Service Location -
@rbusarow class UserScreen : Fragment() { private val viewModel by
lazy { Locator.get<UserViewModel>() } override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Service Location -
@rbusarow class UserScreen : Fragment() { private val viewModel by
lazy { Locator.get<UserViewModel>() } override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Service Location object Locator { inline fun <reified T : ViewModel> get(): T = … } -
@rbusarow class UserScreen : Fragment() { private val presenter by
lazy { Locator.get<UserPresenter>() } private val viewModel by lazy { Locator.get<UserViewModel>() } override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } Service Location object Locator { inline fun <reified T : ViewModel> get(): T = … } -
@rbusarow class UserScreen : Fragment() { private val presenter by
lazy { Locator.instance.get<UserPresenter>() } private val viewModel by lazy { Locator.instance.get<UserViewModel>() } override fun onAttach(context: Context) { Injector.inject(this) super.onAttach(context) } } interface Locator { fun <T : ViewModel> get(): T = … companion object { lateinit var instance: Locator } } Service Location -
class Koin { val graph: Graph fun <T> inject(): Lazy<T>
fun <T> get(): T fun <S, P> bind(s: S): S fun createScope(scopeId: ScopeID, qualifier: Qualifier): Scope } class KoinApplication { val koin = Koin() fun modules(modules: List<Module>): KoinApplication fun logger(logger: Logger): KoinApplication fun unloadModules(modules: List<Module>) fun close() } @rbusarow Koin & KoinApplication -
class Koin { val graph: Graph fun <T> inject(): Lazy<T>
fun <T> get(): T fun <S, P> bind(s: S): S fun createScope(scopeId: ScopeID, qualifier: Qualifier): Scope } class KoinApplication { val koin = Koin() fun modules(modules: List<Module>): KoinApplication fun logger(logger: Logger): KoinApplication fun unloadModules(modules: List<Module>) fun close() } @rbusarow Koin & KoinApplication -
class Koin { val graph: Graph fun <T> inject(): Lazy<T>
fun <T> get(): T fun <S, P> bind(s: S): S fun createScope(scopeId: ScopeID, qualifier: Qualifier): Scope } class KoinApplication { val koin = Koin() fun modules(modules: List<Module>): KoinApplication fun logger(logger: Logger): KoinApplication fun unloadModules(modules: List<Module>) fun close() } @rbusarow Koin & KoinApplication Not an Android Application -
@rbusarow object GlobalContext { internal var app: KoinApplication? = null
fun get(): KoinApplication fun getOrNull(): KoinApplication? fun start(koinApplication: KoinApplication) fun stop() = synchronized(this) { app?.close() app = null } } GlobalContext -
@rbusarow fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create()
GlobalContext.start(koinApplication) appDeclaration(koinApplication) koinApplication.createEagerInstances() return koinApplication } fun koinApplication(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create() appDeclaration(koinApplication) return koinApplication } startKoin & koinApplication -
@rbusarow fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create()
GlobalContext.start(koinApplication) appDeclaration(koinApplication) koinApplication.createEagerInstances() return koinApplication } fun koinApplication(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create() appDeclaration(koinApplication) return koinApplication } startKoin & koinApplication -
@rbusarow fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create()
GlobalContext.start(koinApplication) appDeclaration(koinApplication) koinApplication.createEagerInstances() return koinApplication } fun koinApplication(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.create() appDeclaration(koinApplication) return koinApplication } startKoin & koinApplication -
@rbusarow class MyApplication : Application() { override fun onCreate() {
super.onCreate() } } MyApplication.kt -
@rbusarow class MyApplication : Application() { override fun onCreate() {
super.onCreate() startKoin { // route all Koin logs through android.util.Log androidLogger() } } } MyApplication.kt -
@rbusarow private class TimberLogger(level: Level = Level.INFO) : Logger(level) {
override fun log(level: Level, msg: MESSAGE) { if (this.level <= level) { when (this.level) { Level.DEBUG -> Timber.tag(KOIN_TAG).d(msg) Level.INFO -> Timber.tag(KOIN_TAG).i(msg) Level.ERROR -> Timber.tag(KOIN_TAG).e(msg) } } } } fun KoinApplication.timberLogger(level: Level = Level.INFO): KoinApplication { KoinApplication.logger = TimberLogger(level) return this } TimberLogger.kt -
@rbusarow class MyApplication : Application() { override fun onCreate() {
super.onCreate() Timber.plant(DebugTree()) startKoin { // route all Koin logs through Timber timberLogger() } } } MyApplication.kt -
@rbusarow class MyApplication : Application() { override fun onCreate() {
super.onCreate() Timber.plant(DebugTree()) startKoin { // route all Koin logs through Timber timberLogger() // provide Application context to the graph androidContext(this@MyApplication) } } } MyApplication.kt -
@rbusarow class MyApplication : Application() { override fun onCreate() {
super.onCreate() Timber.plant(DebugTree()) startKoin { // route all Koin logs through Timber timberLogger() // provide Application context to the graph androidContext(this@MyApplication) modules(koinDemoModules) } } } MyApplication.kt -
@rbusarow val dataModule = module { factory { Timber.v("Hello everyone!")
UserRepository().also { Timber.v("Goodbye!") } } } Modules -
@rbusarow val dataModule = module { factory { UserRepository() }
} Modules BeanDefinition Component -
class MyApplication : Application() { override fun onCreate() { super.onCreate()
Timber.plant(DebugTree()) startKoin { // route all Koin logs through Timber timberLogger() // provide Application context to the graph androidContext(this@MyApplication) modules(koinDemoModules) } } } @rbusarow Connecting the Graph -
class MyApplication : Application() { override fun onCreate() { super.onCreate()
Timber.plant(DebugTree()) startKoin { // route all Koin logs through Timber timberLogger() // provide Application context to the graph androidContext(this@MyApplication) modules(koinDemoModules) } } } @rbusarow Connecting the Graph -
@rbusarow val koinDemoModules: List<Module> get() = emptyListOf() val dataModule =
module { factory { UserRepository() } } Connecting the Graph -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule) val dataModule =
module { factory { UserRepository() } } Connecting the Graph -
@rbusarow class UserRepository { internal val database: Database = Database.init(APP_CONTEXT)
internal val okHttpClient: OkHttpClient = OkHttpClient() internal val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://example.dev") .client(okHttpClient) .build() internal val service: UserService = retrofit.create<UserService>() internal val dao: UserDao = database.userDao } Connecting the Graph -
@rbusarow class UserRepository( private val service: UserService, private val dao:
UserDao ) { … } Modules -
@rbusarow val dataModule = module { factory { UserRepository() }
} Connecting the Graph -
@rbusarow val dataModule = module { factory { Repository(service =
get(), dao = get()) } } Modules -
@rbusarow val dataModule = module { factory<UserService> { TODO() }
factory<UserDao> { TODO() } factory { UserRepository(service = get(), dao = get()) } } Connecting the Graph -
val dataModule = module { factory { OkHttpClient() } factory
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory<UserDao> { TODO() } factory { UserRepository(service = get(), dao = get()) } } @rbusarow Connecting the Graph -
val dataModule = module { factory { OkHttpClient() } factory
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory<UserDao> { TODO() } factory { UserRepository(service = get(), dao = get()) } } @rbusarow Connecting the Graph -
val dataModule = module { factory { OkHttpClient() } factory
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory { UserRepository(service = get(), dao = get()) } } @rbusarow Connecting the Graph -
val dataModule = module { factory { OkHttpClient() } factory
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory { UserRepository(service = get(), dao = get()) } } @rbusarow Connecting the Graph -
@rbusarow Connecting the Graph val dataModule = module { factory
{ OkHttpClient() } factory { Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory { UserRepository(service = get(), dao = get()) } } -
@rbusarow Modules val dataModule = module { factory<OkHttpClient> { OkHttpClient()
} factory<Retrofit> { Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory<UserDatabase> { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory<UserRepository> { UserRepository(service = get(), dao = get()) } } -
@rbusarow Modules val dataModule = module { factory<OkHttpClient> { OkHttpClient()
} factory<Retrofit> { Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory<UserDatabase> { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory<UserRepository> { UserRepository(service = get(), dao = get()) } } -
val dataModule = module { factory<OkHttpClient> { OkHttpClient() } factory<Retrofit>
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } factory<UserService> { get<Retrofit>().create<UserService>() } factory<Database> { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } factory<UserRepository> { UserRepository(service = get(), dao = get()) } } @rbusarow Connecting the Graph -
val dataModule = module { single<OkHttpClient> { OkHttpClient() } single<Retrofit>
{ Retrofit.Builder() .baseUrl("https://example.dev") .client(get<OkHttpClient>()) .build() } single<UserService> { get<Retrofit>().create<UserService>() } single<Database> { Database.init(androidContext()) } factory<UserDao> { get<Database>().userDao } single<UserRepository> { UserRepository(service = get(), dao = get()) } } @rbusarow Modules -
@rbusarow class UserScreen { val repository: UserRepository = TODO() }
Accessing the Graph -
@rbusarow class UserScreen : KoinComponent { val repository = get<UserRepository>()
} Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val repository = get<UserRepository>()
} Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val repository = get<UserRepository>()
} class UserViewModel(private val repository: UserRepository) : ViewModel() Accessing the Graph -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, viewModelModule) val viewModelModule
= module { viewModel<UserViewModel> { UserViewModel(repository = get()) } } Accessing the Graph -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, viewModelModule) val viewModelModule
= module { viewModel<ViewModel> { ViewModel(repository = get()) } } Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val viewModel = get<UserViewModel>()
} class UserViewModel(private val repository: UserRepository) : ViewModel() Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val viewModel by viewModel<UserViewModel>()
} class UserViewModel(private val repository: UserRepository) : ViewModel() Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val repository by inject<UserRepository>()
val viewModel by viewModel<UserViewModel>() } class UserViewModel(private val repository: UserRepository) : ViewModel() Accessing the Graph -
@rbusarow class UserScreen : Fragment() { val repository by inject<UserViewModel>()
val viewModel by viewModel<UserViewModel>() } class UserViewModel(private val repository: UserViewModel) : ViewModel() Parameters -
@rbusarow class UserScreen : Fragment() { val repository by inject<UserRepository>()
val viewModel by viewModel<UserViewModel>() } class UserViewModel( private val userId: String, private val repository: UserRepository ) : ViewModel() Parameters -
@rbusarow class UserScreen : Fragment() { val repository by inject<UserRepository>()
val viewModel by viewModel<UserViewModel>() } class UserViewModel( private val userId: String, private val repository: UserRepository ) : ViewModel() val viewModelModule = module { viewModel<UserViewModel> { (userId: String) -> ViewModel(userId = userId, repository = get()) } } Parameters -
@rbusarow class UserScreen : Fragment() { val repository by inject<UserRepository>()
val viewModel by viewModel<UserViewModel> { parametersOf(“50 Cent”) } } class UserViewModel( private val userId: String, private val repository: UserRepository ) : ViewModel() val viewModelModule = module { viewModel<UserViewModel> { (userId: String) -> UserViewModel(userId = userId, repository = get()) } } Parameters -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, scopedModule, viewModelModule) val
scopedModule = module { scoped<Preferences> { Preferences() } } Scope -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, scopedModule, viewModelModule) val
scopedModule = module { scoped<Preferences> { Preferences() } } object Scopes val Scopes.login: StringQualifier get() = named("login") Scope -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, scopedModule, viewModelModule) val
scopedModule = module { scope(scopeName = Scopes.login) { scoped<Preferences> { Preferences() } } } object Scopes val Scopes.login: StringQualifier get() = named("login") Scope -
@rbusarow val koinDemoModules: List<Module> get() = listOf(dataModule, scopedModule, viewModelModule) val
scopedModule = module { scope(scopeName = Scopes.login) { scoped<Preferences> { Preferences() } } } class Anywhere : KoinComponent { val loginScope = getKoin().createScope(Scopes.login, named("login")) val preferences by loginScope.inject<Preferences>() } Scope -
@rbusarow class Screen : Fragment() { val presenter by currentScope.inject<Presenter>()
val viewModel by viewModel<ViewModel>() } val scopedModule = module { scope(named<Screen>()) { scoped<Presenter> { Presenter() } } scope(scopeName = Scopes.login) { scoped<Preferences> { Preferences() } } } Parameters -
@rbusarow internal class UserRepositoryTest { val service = mockk<UserService>() val
dao = mockk<UserDao>() lateinit var repo: UserRepository @BeforeEach fun beforeEach() { repo = UserRepository(service, dao) } } Testing -
@rbusarow internal class UserRepositoryTest : KoinTest { val service =
mockk<UserService>() val dao = mockk<UserDao>() lateinit var repo: UserRepository @BeforeEach fun beforeEach() { repo = UserRepository(service, dao) } } Testing -
@rbusarow internal class UserRepositoryTest : KoinTest { … @BeforeEach fun
beforeEach() { startKoin { modules(koinDemoModules) } repo = get<UserRepository>() } @AfterEach fun afterEach() { getKoin().close() } } Testing -
@rbusarow internal class UserRepositoryTest : KoinTest { … val mocks
= module(override = true) { single<UserService> { service } single<UserDao> { dao } } @BeforeEach fun beforeEach() { startKoin { modules(koinDemoModules) } repo = get<UserRepository>() } @AfterEach fun afterEach() { getKoin().close() } } Testing -
@rbusarow internal class UserRepositoryTest : KoinTest { … val mocks
= module(override = true) { single<UserService> { service } single<UserDao> { dao } } @BeforeEach fun beforeEach() { startKoin { modules(koinDemoModules) modules(mocks) } repo = get<UserRepository>() } … } Testing -
@rbusarow internal class ModuleTest : KoinTest { @BeforeEach fun beforeEach()
{ startKoin { modules(koinDemoModules) } } @AfterEach fun afterEach() { getKoin().close() } @Test fun `check modules`() { getKoin().checkModules() } } Testing -
@rbusarow Further Reading http://bit.ly/322XZr5 http://bit.ly/2L2IfO4 Koin Android documentation: Koin Core
documentation: Koin Github: http://bit.ly/2ZkTk2d