https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
koin
  • d

    Davide Giuseppe Farella

    08/29/2020, 2:00 PM
    I don’t want different classifier, I wanna be able to do both:
    get<MyClass>()
    get<MyClass> { parametersOf(MyParams(...)) }
    a
    • 2
    • 5
  • w

    William Lindblom

    08/31/2020, 12:57 PM
    I am testing a module where the top level has parameters. I use checkModules with parameters, but the test only seems to pass some times, most times i get an error that it "Can't get parameter value #0". The following is a sample with the same issue. Anyone who can tell if I'm using it wrong?
    import org.junit.experimental.categories.Category
    import org.junit.jupiter.api.Test
    import org.koin.core.parameter.parametersOf
    import org.koin.dsl.module
    import org.koin.test.AutoCloseKoinTest
    import org.koin.test.category.CheckModuleTest
    import org.koin.test.check.checkModules
    
    interface First
    class FirstImpl(a: String) : First
    
    interface Second
    class SecondImpl(a: First) : Second
    
    @Category(CheckModuleTest::class)
    internal class KoinTest : AutoCloseKoinTest() {
    
        @Test
        fun checkModules() {
            val testModule = module {
                single<Second> { SecondImpl(get()) }
                single<First> { (foo: String) -> FirstImpl(foo) }
            }
    
            checkModules(parameters = { create<First> { parametersOf("hello") } }) {
                modules(testModule)
            }
        }
    }
    • 1
    • 1
  • s

    Slackbot

    08/31/2020, 3:36 PM
    This message was deleted.
    t
    b
    a
    • 4
    • 30
  • n

    nikolaymetchev

    09/04/2020, 9:42 AM
    Hello Everyone, We are thinking of upgrading to Kotlin 1.4. Currently our app fails unless we use the version
    2.2.0-alpha-1
    of koin. Is there any visibility as to when a proper release of 2.2.0 will be available?
    a
    z
    • 3
    • 7
  • a

    aipok

    09/07/2020, 9:11 AM
    Looking into 2.2.0-beta-1 and trying to achieve the same result I had with 2.1.6. Seeing the following issue using new
    ScopeActivity
    and
    ScopeFragment
    API’s… • While using shared instance for activity and share it to all the fragments, it is not clear how to instantiate
    sharedViewModel
    inside fragments that was created by activity. Looks like this API is not available anymore. I was able to achieve same result by using
    scopeActivity?.let {
        viewModel = it.getViewModel<SomeViewModel>()
    }
    is that the way to do this now?
    • Another pain point is to inject instances using
    scopeActivity
    into lazy properties. They are became nullable by default. Is it might be possible to use Fragment’s
    requireActivity()
    method for getting
    requireScopeActivity
    which is not nullable. Otherwise I have to insert
    ?
    everywhere in my code then using property initialized like this
    protected val imm by lazy {
        scopeActivity?.get<InputMethodManager> {
            parametersOf(requireActivity())
        }
    }
    • In order to instantiate something that do not require scope from
    ScopeActivity
    or
    ScopeFragment
    should I use
    GlobalContext
    or
    ScopeActivity.koin
    calls? It is a bit confusing that default
    get
    or
    inject
    in
    ScopeActivity
    and
    ScopeFragment
    subclasses are trying to get instance from its
    scope
    . From what I have, usually I’m getting some factory instances by default without any
    scope
    and some specific (more like a rare) scoped injections. I would prefer to have
    scope.get
    /
    scope.inject
    and default
    get
    /
    inject
    to be
    koin.get
    koin.inject
    . Not sure might be thats only my opinion and other developers are using it opposite. Fill free to open discussion and drop your comments. I would happy to hear any suggestions or ways to use Koin
    scope
    system or
    sharedViewModel
    definition. Thanks!
    a
    • 2
    • 1
  • a

    arnaud.giuliani

    09/09/2020, 7:33 AM
    Koin MP
    3.0.0-alpha-3
    is out 👍
    🎉 9
    g
    • 2
    • 5
  • a

    arnaud.giuliani

    09/09/2020, 9:30 AM
    metadata fixed in
    3.0.0-alpha-4
    🎉 4
    i
    • 2
    • 1
  • j

    Javier

    09/09/2020, 9:45 AM
    Do you know when there will be available an alpha with the compose branch?
    a
    • 2
    • 4
  • n

    nikolaymetchev

    09/10/2020, 5:48 PM
    Hello, I am trying to parallelize our unit tests. I am finding that koin is not really designed to be run in a multi-threaded environment. We want to run tests in parallel and each test needs to create it’s own instance of the application and tear it down at the end of each test. Is there any examples of anyone doing this?
    s
    m
    • 3
    • 3
  • m

    Mark

    09/13/2020, 2:16 AM
    Curious if anyone has any thoughts about this https://proandroiddev.com/getting-rid-of-koin-or-how-i-never-learnt-to-stop-worrying-and-love-the-dependency-injection-ee8fe0f4081d
    a
    k
    h
    • 4
    • 6
  • p

    Peter Farlow

    09/14/2020, 9:01 PM
    I have some Android instrumentation tests and a dependency declared in a module. In most of our tests, we want the normal dependency. But in one test file, we want to inject a mock version of the dependency. What's the best way to inject a mock dependency and then make sure to replace it with the normal dependency after the tests in that file are complete?
    m
    a
    • 3
    • 9
  • a

    aipok

    09/16/2020, 12:41 PM
    I’m having issue with
    override val scope: Scope by lazy { koin.createScope(scopeID, getScopeName(), this) }
    in my child fragment which extends from
    ScopeFragment
    . For some reason it gives me else condition and exception
    NoScopeDefFoundException
    from
    onViewCreated
    method.
    val scopeDefinition = _scopeDefinitions[qualifier.value]
            return if (scopeDefinition != null) {
                val createdScope: Scope = createScope(scopeId, scopeDefinition, source)
                _scopes[scopeId] = createdScope
                createdScope
            } else {
                throw NoScopeDefFoundException("No Scope Definition found for qualifer '${qualifier.value}'")
            }
    Should I declare each fragment scope in my module before I can use or why I could get this error in
    2.2.0-beta-1
    version? Also it seem to call
    createScope
    and fail in
    onViewCreated
    because of this line
    koin._logger.debug("Open fragment scope: $scope")
    in
    ScopeFragment
    Update: after a bit of tries. If I declare scope for a fragment like this
    scope(named<ChildFragment>()) {  }
    It still not work, but I remember it was mentioned that empty declarations will not be allowed… so it works it I declare something scoped
    scope(named<ChildFragment>()) {
        scoped { (activity: BaseActivity) -> CustomTabsHelper(activity) }
    }
    But this is very weird that I have to declare scope before the fragment
    createScope
    . My assumption was that each
    ScopeFragment
    is able to create its own scope and I can use that scope anytime I need it. Since all my fragment as extended from the same BaseFragment or similar. This is very unusable since I can’t extend from
    ScopeFragment
    only on some of them. From other hand declaring useless scopes in modules for each and every fragment I have this is even more work. Not sure what was the idea behind this change. With lifecycle it was much easier (like is it if you need it or just skip it). As usual any feedback or discussions are welcome 😄 Koin is the best anyway 🤟
    s
    a
    • 3
    • 22
  • w

    willyrs

    09/18/2020, 8:23 AM
    not sure if this belongs here, but I’ve created a new project with kotlin 1.4 and pasted the gradle file that I used with 1.3.72 and I have this error only on the koin library.. what can be the cause? This is a multiplatform project
    j
    • 2
    • 5
  • a

    arnaud.giuliani

    09/25/2020, 1:31 PM
    Koin 2.2.0-beta-2 is published - https://github.com/InsertKoinIO/koin/blob/master/CHANGELOG.md#220-beta-2
    🎉 5
    j
    j
    • 3
    • 7
  • c

    coroutinedispatcher

    09/27/2020, 5:39 PM
    If I would have a
    MainActivity
    that implements
    MainActivityInteraction
    interface, and many fragments need this interface in order to communicated with the
    MainActivity
    , using koins
    fragmentFactory
    , is that achievable? I cannot actually do:
    single {MainActivity()} binds arrayOf(MainActivityInteractions::class)
    fragment {BlaBlaFragment(get())} // should get the interface above
    Because it's dangerous. Short question, how can I achieve interface communication between fragments and a single activity with koin
    t
    • 2
    • 4
  • a

    arnaud.giuliani

    09/28/2020, 9:38 AM
    https://kotlinlang.slack.com/archives/CJLTWPH7S/p1601067741085300
    j
    • 2
    • 3
  • j

    Joaquim Ley

    09/29/2020, 1:51 PM
    Hello fellow koiners 👋 This is regarding multiplatform, as anyone managed to do constructor injection on the Swift/iOS part? So for my specific use case, I want to inject a executor/usecase into a Swift class. The issue is this executor has a dependency and so on and forth, on Android is quite simple as we just need to declare the modules and use
    by viewModel()
    or wtv it suits you, you could even
    inject()
    but on Swift seems like we don't have access to Koin's sugar. -- Summarising: View wants to create a ViewModel <- UseCase <- Repository <- RemoteApi Note: '<-' Depends on
    s
    z
    • 3
    • 4
  • s

    sloydev

    10/07/2020, 2:52 PM
    Hi there! I think I just found a concurrency issue in Koin. After a few weeks hunting a crash we were having in production, I found out that Koin was sometimes creating more than one instance of a dependency declared as
    single
    . I've isolated the issue to a concurrency bug in
    SingleInstanceFactory
    . I have an (ugly) test reproducing it, and a possible solution. It's tricky because the probability of happening is very low, but it happens ^^' @arnaud.giuliani would you like me to open a PR? Or do you prefer to discuss it here before?
    a
    • 2
    • 11
  • s

    sahil Lone

    10/08/2020, 8:30 AM
    Guys,  I had started a library last year to have a wrapper over Jackson for a type safe programming. Please have. a look at it, remarks are highly appreciated and. if you believe it can. be taken further please help to contribute or give it a star if you like it. https://github.com/sahlone/kson
    👎 2
    t
    p
    j
    • 4
    • 3
  • t

    tarek

    10/09/2020, 1:32 PM
    Hi, Is there a way to inject directly into UIViewController classes?
    r
    • 2
    • 2
  • d

    dagomni

    10/09/2020, 3:46 PM
    How does Koin compare to Kodein or kotlin-inject in Multiplatform projects currently? Are there any notable limits/restrictions to any one of them?
    a
    • 2
    • 1
  • n

    nrobi

    10/12/2020, 10:24 AM
    Anyone having issues with injecting into `@Composable`s? Using
    koin 2.2.0-rc-2
    with
    kotlin 1.4.10
    . More details in thread
    • 1
    • 2
  • s

    Saul Wiggin

    10/12/2020, 10:52 AM
    I’ve added the android name in the manifest and now getting errors that
    Unable to start activity ComponentInfo{com.example.cakesapimvvm/com.example.cakesapimvvm.MainActivity}: org.koin.core.error.InstanceCreationException: Could not create instance for [Factory:'com.example.cakesapimvvm.viewmodel.CakeListViewModel']
    j
    f
    • 3
    • 9
  • a

    arnaud.giuliani

    10/13/2020, 11:55 AM
    while waiting for the 2.2.0 stable release, here are some notes about this new release: https://medium.com/koin-developers/whats-next-with-koin-2-2-3-0-releases-6c5464ae5e3d
    👏 7
    👍 3
    a
    z
    • 3
    • 11
  • n

    nrobi

    10/14/2020, 10:17 AM
    Anyone used
    getViewModel()
    in a composable, where the parameters of the vm are subject to change?
    a
    • 2
    • 13
  • k

    Krystian Rybarczyk

    10/14/2020, 2:44 PM
    Hey guys, I’m writing a functional tests in ktor. One of the suites works absolutely fine and the other one fails to start when `
    withTestApplication({ module() }) {
    is executed. The error is:
    No definition found for class:'com.alpha.CoolService'. Check your definitions!
    org.koin.core.error.NoBeanDefFoundException
    The bean is definitely there. As I mentioned it works fine in the other test suite. When I stopped there with the debugger there were no beans to be found indeed.
    CoolService
    is just the first been that I try to retrieve with
    get()
    . It seems that the context is somehow screwed up. Could it be that the separate ktor test suites are messing up each others Koin contexts?
    a
    • 2
    • 2
  • t

    tieskedh

    10/15/2020, 9:34 AM
    I've a small question: Is this the correct workaround for compose not yet being implemented in 3.0.0-alpha-4:
    @Composable
    inline fun <reified T : ViewModel> viewModel(
        qualifier: Qualifier? = null,
        noinline parameters: ParametersDefinition? = null
    ): Lazy<T> {
        val owner = ViewModelStoreOwnerAmbient.current.viewModelStore
        return remember {
            KoinContextHandler.get().getViewModel(
                owner = { owner },
                qualifier = qualifier,
                parameters = parameters
            )
        }
    }
    a
    • 2
    • 1
  • s

    Saul Wiggin

    10/15/2020, 10:17 AM
    Trying to implement Koin unsuccessfully. Getting the following error. I’ve uncommented a line in the fragment
    binding.viewmodel = viewModel
    where previously the error was Koin not correctly configured.
    a
    • 2
    • 8
  • j

    Javier

    10/19/2020, 11:55 AM
    The only way to get the current activity context is using parameters when it is being injected?
    t
    • 2
    • 14
  • s

    sebastien.rouif

    10/20/2020, 12:10 PM
    Hi, I have a scope in which multiple classes rely on a unique mapId in this scope. I’m trying to find a nice way of injecting it throughout the scope. I can define my mapIdProvider in my scope as follow :
    scoped { (mapId: String) -> MapIdProvider(mapId = mapId) }
    but I need to call
    myScope.get { parametersOf(getMapId()) }
    directly after the scope creation so that the mapId is passed to the bean definition. It seems that
    Scope
    class can also have some parameters so I tried
    koin.createScope<RootActivityScopeKey>().also {
        it.addParameters(parametersOf(getMapId()))
    }
    but then I get
    Can't get injected parameter #0 from DefinitionParameters[] for type 'java.lang.String'
    I tried removing the definition in the scope adding the
    koin.createScope<RootActivityScopeKey>().also {
        it.addParameters(parametersOf(MapIdProvider(getMapId())))
    }
    but no success either. Is there a better way to inject that
    MapIdProvider
    ? note that
    MapIdProvider
    is just a dataClass that holds the mapId
    t
    • 2
    • 6
Powered by Linen
Title
s

sebastien.rouif

10/20/2020, 12:10 PM
Hi, I have a scope in which multiple classes rely on a unique mapId in this scope. I’m trying to find a nice way of injecting it throughout the scope. I can define my mapIdProvider in my scope as follow :
scoped { (mapId: String) -> MapIdProvider(mapId = mapId) }
but I need to call
myScope.get { parametersOf(getMapId()) }
directly after the scope creation so that the mapId is passed to the bean definition. It seems that
Scope
class can also have some parameters so I tried
koin.createScope<RootActivityScopeKey>().also {
    it.addParameters(parametersOf(getMapId()))
}
but then I get
Can't get injected parameter #0 from DefinitionParameters[] for type 'java.lang.String'
I tried removing the definition in the scope adding the
koin.createScope<RootActivityScopeKey>().also {
    it.addParameters(parametersOf(MapIdProvider(getMapId())))
}
but no success either. Is there a better way to inject that
MapIdProvider
? note that
MapIdProvider
is just a dataClass that holds the mapId
t

tynn

10/20/2020, 12:22 PM
You could use
createScope(id, source)
and provide the
mapId
as source there. Then it should be possible to crate the MapIdProvider as
scoped { MapIdProvider(mapId = getSource()) }
s

sebastien.rouif

10/20/2020, 1:51 PM
I’ll try that
@Suppress("UNCHECKED_CAST")
private fun <T : Any> resolveInstance(
        qualifier: Qualifier?,
        clazz: KClass<T>,
        parameters: ParametersDefinition?
): T {
    if (_closed) {
        throw ClosedScopeException("Scope '$id' is closed")
    }
    val indexKey = indexKey(clazz, qualifier)
    return _instanceRegistry.resolveInstance(indexKey, parameters)
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope")
                getFromSource(clazz)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope's source")
                _parameters?.getOrNull<T>(clazz)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in injected parameters")
                findInOtherScope<T>(clazz, qualifier, parameters)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in linked scopes")
                throwDefinitionNotFound(qualifier, clazz)
            }
}
reading the code I don’t understand why it would be better from source or from _parameters
t

tynn

10/20/2020, 2:02 PM
I think
source
is cleaner and a bit more generic.
s

sebastien.rouif

10/20/2020, 3:24 PM
Thanks @tynn, I’m not sure why the parameter parts doesn’t work but the source one works like a charm
View count: 21