Skip to content

Instantly share code, notes, and snippets.

@rubenpla-develop
Forked from fredy-mederos/KoinJavaUtils.kt
Created October 24, 2018 16:35
Show Gist options
  • Select an option

  • Save rubenpla-develop/9e888e18320a44a687c93a5c8d6fb513 to your computer and use it in GitHub Desktop.

Select an option

Save rubenpla-develop/9e888e18320a44a687c93a5c8d6fb513 to your computer and use it in GitHub Desktop.

Revisions

  1. @fredy-mederos fredy-mederos created this gist Mar 27, 2018.
    59 changes: 59 additions & 0 deletions KoinJavaUtils.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    package com.common.utils

    import org.koin.KoinContext
    import org.koin.standalone.StandAloneContext
    import kotlin.jvm.internal.Reflection


    /**
    * @author @fredy_mederos
    */
    object KoinJavaUtils {

    /**
    * inject lazily given dependency
    */
    @JvmOverloads
    @JvmStatic
    fun <T> inject(clazz: Class<T>, name: String = ""): Lazy<T> {
    return lazy { get(clazz, name) }
    }

    /**
    * Retrieve given dependency
    */
    @JvmOverloads
    @JvmStatic
    fun <T> get(clazz: Class<T>, name: String = ""): T {
    val kclazz = Reflection.getOrCreateKotlinClass(clazz)
    val koinContext = (StandAloneContext.koinContext as KoinContext)

    val beanDefinition = if (name.isBlank())
    koinContext.beanRegistry.searchAll(kclazz)
    else
    koinContext.beanRegistry.searchByName(name)

    return koinContext.resolveInstance(kclazz, { emptyMap() }, { beanDefinition }) as T
    }

    /**
    * inject lazily given property
    */
    @JvmOverloads
    @JvmStatic
    fun <T> property(key: String, defaultValue: T? = null): Lazy<T?> {
    return lazy { getProperty(key, defaultValue) }
    }

    /**
    * Retrieve given property
    */
    @Suppress("UNCHECKED_CAST")
    @JvmOverloads
    @JvmStatic
    fun <T> getProperty(key: String, defaultValue: T? = null): T? {
    val koinContext = (StandAloneContext.koinContext as KoinContext)
    return koinContext.propertyResolver.properties[key] as T? ?: defaultValue
    }

    }