Skip to content

Instantly share code, notes, and snippets.

View rygelouv's full-sized avatar

Rygel Louv rygelouv

View GitHub Profile
data class Transaction(
val id: Long?,
val amount: Double?,
val currency: Currency?,
val reference: String?,
val transactiontype: String?,
val direction: String?,
val correspondent: TransactionCorrespondent?,
val beginDate: Long? = 0,
val endDate: Long? = 0,
val List<Module>.declarationRegistry: Map<KClass<*>, Declaration<Any>>
get() = this.fold(this[0].declarationRegistry) { acc, module -> (acc + module.declarationRegistry) as MutableMap<KClass<*>, Declaration<Any>> }
class UseCase(private val repo: Repository) {
fun execute() = repo.getText()
}
class Repository {
fun getText() = "Text from repository"
}
class ViewModel( private val useCase: UseCase) {
fun showText() {
class ServiceLocator {
private val serviceMap: MutableMap<KClass<*>, Service> = ConcurrentHashMap()
fun <T : Any> getService(clz: KClass<T>): Service {
return serviceMap[clz] ?: error("Unable to find definition of $clz")
}
private fun addService(service: Service) {
serviceMap[service.type] = service
fun <T: Any> Declaration<T>.toService(): Service {
val instance: T = this()
return DefaultService.createService(instance)
}
object LiteKoinContext {
private val liteKoin = LiteKoin()
fun modules(modules: List<Module>) {
liteKoin.loadModules(modules)
}
fun getLiteKoin() = liteKoin
}
fun getLiteKoin() = LiteKoinContext.getLiteKoin()
inline fun <reified T: Any> get(): T {
val service = getLiteKoin().resolveInstance(T::class)
return service.instance as T
}
inline fun <reified T: Any> inject(): Lazy<T> = lazy { get<T>() }
class LiteKoin {
private val registry = ServiceLocator()
lateinit var declarations: Map<KClass<*>, Declaration<Any>>
fun loadModules(modules: List<Module>) {
declarations = modules.declarationRegistry
registry.loadModules(modules)
}
inline fun <reified T: Any> get(): T {
val declaration = declarationRegistry[T::class]
var instance = declaration?.invoke()
if (instance == null) {
val liteKoin = LiteKoinContext.getLiteKoin()
instance = liteKoin.declarations[T::class]?.invoke() ?: error("Unable to find declaration of type ${T::class.qualifiedName}")
}
return instance as T
}
fun module(block: Module.() -> Unit) = Module().apply(block)