Skip to content

Instantly share code, notes, and snippets.

@qwert2603
Last active July 6, 2024 02:21
Show Gist options
  • Save qwert2603/4321d68d5408165794f3ede4ade6c18d to your computer and use it in GitHub Desktop.
Save qwert2603/4321d68d5408165794f3ede4ade6c18d to your computer and use it in GitHub Desktop.
import org.koin.core.Koin
import org.koin.core.context.startKoin
import org.koin.core.module.Module
import org.koin.core.qualifier.Qualifier
import org.koin.core.qualifier.named
import org.koin.dsl.module
import org.koin.dsl.onClose
import org.koin.ext.getFullName
// Based on Koin 3.1.2
@PublishedApi
internal class Multibinding<K, V> : MutableMap<K, V> by mutableMapOf()
inline fun <reified K, reified V> multibindingQualifier(): Qualifier =
named("${K::class.getFullName()}_${V::class.getFullName()}")
inline fun <reified K, reified V> Module.declareMultibinding() {
single(qualifier = multibindingQualifier<K, V>()) {
Multibinding<K, V>()
}
}
inline fun <reified K, reified V> Module.intoMultibinding(key: K, value: V) {
var multibinding: Multibinding<K, V>? = null
single(
qualifier = named("${K::class.getFullName()}_${V::class.getFullName()}_$key"),
createdAtStart = true,
) {
multibinding = get(multibindingQualifier<K, V>())
multibinding!![key] = value
}.onClose {
multibinding?.remove(key)
}
}
inline fun <reified K, reified V> Koin.getMultibinding(): Map<K, V> =
get<Multibinding<K, V>>(qualifier = multibindingQualifier<K, V>()).toMap()
fun main() {
val koin = startKoin {
val module1 = module {
declareMultibinding<String, Int>()
intoMultibinding("one", 1)
intoMultibinding("two", 2)
intoMultibinding("three", 3)
declareMultibinding<String, Double>()
intoMultibinding("one", 1.0)
}
val module2 = module {
intoMultibinding("six", 6)
intoMultibinding("seven", 7.0)
declareMultibinding<Float, Unit>()
intoMultibinding(3.14f, Unit)
}
modules(module1, module2)
}.koin
println(koin.getMultibinding<String, Int>()) // {one=1, two=2, six=6, three=3}
println(koin.getMultibinding<String, Double>()) // {seven=7.0, one=1.0}
println(koin.getMultibinding<Float, Unit>()) // {3.14=kotlin.Unit}
val module3 = module {
intoMultibinding("seven", 7)
}
koin.loadModules(listOf(module3))
println(koin.getMultibinding<String, Int>()) // {one=1, two=2, six=6, three=3, seven=7}
koin.unloadModules(listOf(module3))
println(koin.getMultibinding<String, Int>()) // {one=1, two=2, six=6, three=3}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment