Skip to content

Instantly share code, notes, and snippets.

@dellisd
Created April 24, 2021 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dellisd/cffe1631372ab867357810f182e4919e to your computer and use it in GitHub Desktop.
Save dellisd/cffe1631372ab867357810f182e4919e to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.runBlocking
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import org.koin.dsl.module
class SharedAny(private val provider: suspend () -> Any) {
private var any: Any? = null
suspend operator fun <R> invoke(block: (Any) -> R): R {
if (any == null) {
any = provider()
}
return block(any!!)
}
}
suspend fun provideAny(): Any {
return Any()
}
class AnyConsumer(private val withAny: SharedAny) {
suspend fun doThing() = withAny { any ->
println(any)
}
}
val myModule = module {
// Doesn't work
single { ::provideAny }
// ::provideAny must be provided manually
single { SharedAny(::provideAny) }
single { AnyConsumer(get()) }
}
class Application : KoinComponent {
private val consumer by inject<AnyConsumer>()
fun run() = runBlocking {
consumer.doThing()
}
}
fun main() {
startKoin {
printLogger()
modules(myModule)
}
Application().run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment