https://kotlinlang.org logo
Title
r

Rafal

04/04/2023, 10:58 AM
I'm kinda new to koin, also I'm lazy so sometimes I'm making private extensions in my modules. Is there any downside to this approach? Or is it ok to extend
Scope
that way
private val Scope.bffApiKey: String
    get() = get(named(BFF_API_KEY))

single {
    ApiClass(
       apiKey=bffApiKey,
    )
}
m

Matt Rea

04/04/2023, 8:30 PM
I add little extensions like this too. Only downside is that they often get broken by koin updates 🙃
a

Adam Brown

04/05/2023, 4:03 AM
I do something some what similiar:
val mainModule = module {
    ...
    // This is a scope that is created & destroyed, possibly multiple times during lifetime of process
    scope<ProjectDefScope> {
        // IdRepositoryOkio takes in a `ProjectDef` as a ctor argument
        scopedOf(::IdRepositoryOkio) bind IdRepository::class
    }
}
ProjectDef
is the thing I care about, it is injected via constructor. Each one of the things injected in this scope inherit from
ProjectScoped
abstract class IdRepository(private val projectDef: ProjectDef) : ProjectScoped {
    override val projectScope = ProjectDefScope(projectDef)
    // This custom inject does the work
    private val projectSynchronizer: ClientProjectSynchronizer by projectInject()
    ...
And then I have the ext function
projectInject
that grabs the
projectDef
and passes it as an argument to the
inject
call.
interface ProjectScoped : KoinComponent {
	val projectScope: ProjectDefScope
}

/**
 * Injects objects from the Project Scope which all require a ProjectDef
 * parameter during injection.
 */
inline fun <reified T : Any> ProjectScoped.projectInject(
	qualifier: Qualifier? = null,
	mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(),
	noinline parameters: ParametersDefinition? = null
): Lazy<T> =
	lazy(mode) {
		val newParameters = if (parameters != null) {
			val params = parameters()
			parametersOf(arrayOf(params.values.toMutableList().add(projectScope.projectDef)))
		} else {
			parametersOf(projectScope.projectDef)
		}
		projectScope.get<T>(qualifier) { newParameters }
	}