https://kotlinlang.org logo
Docs
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
dagger
  • g

    ghedeon

    01/30/2019, 12:14 PM
    Trying to debug dagger modules in a multimodule project. Let say,
    app
    gradle module depends on
    feature
    gradle module. When I define my
    featureModule
    in the
    feature
    , it fails to generate provide methods, but it works if I move it to the
    app
    .
    g
    • 2
    • 3
  • g

    ghedeon

    02/01/2019, 12:54 AM
    I'm stuck with multi-module setup (
    app
    gradle module depends on
    feature
    library module). The general advice that I often see: if you don't want to get lost in dagger — don't bring Components to the library modules. It's easier if you just connect all your dagger modules from libraries in the final
    app
    module under one Component. That works, up to a point. Let say you need to do some manual injection in one of the libraries. But Component is in the
    app
    , so you don't have a direct reference. What are my options here?
    d
    j
    d
    • 4
    • 35
  • k

    kingsley.gomes

    03/15/2019, 3:21 PM
    Hi, I'm trying to import and use an aar(which contains Operations.kt) into a project. The aar uses Dagger2 for its dependencies. When i try to inject it in the project i get the following error. Any help would be highly appreciated
    e: error: compiler message file broken: key=compiler.err.Processor: org.jetbrains.kotlin.kapt3.base.ProcessorWrapper@16547060 arguments={0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}
    e: error: cannot access Operations
      class file for com.Operations not found
      Consult the following stack trace for details.
      com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.Operations not found
    :app:kaptDebugKotlin FAILED
    h
    • 2
    • 5
  • j

    juliocbcotta

    03/21/2019, 4:04 AM
    Is it possible to provide generics types using
    @IntoSet
    ? Like...
    @IntoSet fun provideFooBar(): Foo<Bar> ...
    and collect it using something like
    val mySet: Set<@JvmSuppressWildcards Foo<Bar>>
    ?
    g
    b
    • 3
    • 6
  • a

    amrelmasry

    04/08/2019, 10:58 AM
    Kapt doesn't generate dagger code in androidTest folder:
    // build.gradle.kts
    plugins {
        id("kotlin-kapt")
    }
    
    dependencies {
        // ...
        kapt(Libs.DAGGER_PROCESSOR) // this works fine
        kaptAndroidTest(Libs.DAGGER_PROCESSOR) // this doesn't work
    }
    
    
    class Test { 
    
    @Module
    class DummyModule
    
    @Component(modules = [DummyModule::class])
    interface DummyComponent {
    
    }
    }
    • 1
    • 1
  • w

    william

    04/09/2019, 11:36 AM
    any recommended ways about eagerly creating a dagger provided object? i probably don't want dagger to create it, but in my application i have an
    @Inject
    field that is never used just so my object gets created - this seems odd though
    g
    p
    • 3
    • 10
  • k

    Kavin

    04/13/2019, 1:39 PM
    I'm beginner, can any one guide me to some good list of articles or tutorials for dagger?
    b
    d
    +2
    • 5
    • 6
  • k

    Kavin

    06/18/2019, 6:03 AM
    Dagger + Kotlin - I’m getting
    lateinit property has not been initialized error
    . I believe I have done everything but not sure what’s missing!
    g
    • 2
    • 1
  • k

    Kavin

    06/18/2019, 6:07 AM
    This is what my code looks like
    Untitled.kt
    g
    • 2
    • 16
  • g

    gumil

    07/29/2019, 12:12 PM
    Why does generated classes in dagger does not count as a source set when it is only a kotlin module? On Android modules makes the generated directory as a sourceset by default
    • 1
    • 1
  • j

    Jacob Richards

    09/16/2019, 6:05 AM
    can anyone recommend a resource for getting started with dagger in kotlin (NOT with android, I’m building a web server)?
    g
    • 2
    • 4
  • j

    jw

    09/24/2019, 2:57 PM
    Hey all. We're starting to land some Kotlin-specific changes into Dagger! Two have already landed which will be in the next release: - Understand qualifier annotations on properties without requiring a use-site target (i.e.,
    @Whatever
    instead of
    @field:Whatever
    ) - Understand
    @Module
    on
    object
    does not require a module instance. We have a few more in the pipeline, but if you have any ideas of small ergonomic improvements like this please file an issue on GitHub.
    🎉 34
    👽 2
    👍 9
    ❤️ 4
    z
    a
    +2
    • 5
    • 15
  • g

    ghedeon

    09/25/2019, 6:59 AM
    What is the recommended way of having a DebugComponent that extends MainComponent with some extra modules in debug? Thank you.
    h
    r
    • 3
    • 3
  • r

    ritesh

    10/05/2019, 7:18 PM
    @JvmStatic @Provides @Singletonn fun providesHandler( ): SomeHandler = HandlerObject.init() This is the provider, i have inside the some module and that module is sits in the application component and it's singleton. I know that dagger generates all the module providers classes at compile time, as gets the instance dependency through the
    get()
    overriden method in the class. As all classes required for the DI graph are created at compile time. I was wondering when the actual creation of the object happens, when
    get()
    is actually called. Does it gets called and object is created when it's requested through
    @inject
    or happens at compile time and just returns when
    @inject
    gets called.
    w
    • 2
    • 2
  • a

    arekolek

    10/25/2019, 4:18 PM
    why no thermosiphon example? :troll:
    😄 4
    m
    • 2
    • 1
  • f

    furkan.akdemir

    10/27/2019, 9:17 PM
    Is it ok to use dagger in a library ? I haven't seen much example of it, however, there is a little section about it in Android docs.
    p
    • 2
    • 1
  • j

    jw

    10/27/2019, 9:18 PM
    You just have to shade it
    f
    • 2
    • 1
  • p

    Paul Woitaschek

    11/05/2019, 8:46 AM
    How would I use dagger-reflect with a pure kotlin module? For the android modules I have set a
    Dev
    build type where I use dagger reflect and the
    Debug
    and
    Release
    build types use the regular dagger.
    w
    • 2
    • 5
  • m

    Manuel Vivo

    12/18/2019, 4:36 PM
    For a 101 cheatsheet of what code Dagger generates for you, check out this tweet: https://twitter.com/manuelvicnt/status/1207337679144259590
    👏 2
    ❤️ 8
    👍 3
    p
    • 2
    • 2
  • k

    kyleg

    01/26/2020, 7:13 PM
    Can one inject functions using Dagger? I replaced an injectable class that was the command pattern with a function. As a class in the command pattern, the app builds. As the function, I get an error at point of injection
    [Dagger/MissingBinding]
    fun AddUseCase(x: Int): Reader<ReturnValType> = MyReader { ctx -> /* ... */ }
    versus
    class AddUseCase(ctx: MyContext) {
      fun invoke(x: Int): ReturnValType { /* ... */ }
    }
    w
    t
    • 3
    • 3
  • j

    jw

    02/04/2020, 2:00 PM
    you can always have unscoped providers
    👍 1
    s
    • 2
    • 1
  • j

    Jovan

    02/10/2020, 9:52 PM
    Hi guys. Recently I started working on new project and I wanted to start with mudularization right away. So far so good, however, I had a hard time implementing Dagger. Here is the thing. I have :app, :onboarding, :core as features, where :app depends on :onboarding and :*core*. :onboarding depends only on :core. :core doesn’t have any dependency. Regarding Dagger I have the following implementation.
    @Module
    class CoreModule {
    
        @Provides
        @AppScope
        fun provideLogger(): Logger {
            ...
        }
    
        @Provides
        @AppScope
        fun provideApiService(serviceHolder: ServiceHolder, OkHttpClientBuilder: OkHttpClientBuilder): APIService {
            ...
        }
    }
    @Component(
        modules = [
            AndroidSupportInjectionModule::class,
            CoreModule::class,
            MainActivityModule::class
        ]
    )
    @AppScope
    interface AppComponent: AndroidInjector<MainApplication> {
        @Component.Factory
        interface Factory {
            fun create(@BindsInstance applicationContext: Context): AppComponent
        }
    }
    @Module
    abstract class MainActivityModule {
        @ContributesAndroidInjector(modules = [OnBoardingModule::class])
        @ActivityScope
        abstract fun mainActivity(): MainActivity
    }
    @Module
    abstract class OnBoardingModule {
        @ContributesAndroidInjector(modules = [SignInModule::class])
        abstract fun signInFragment(): SignInFragment
    }
    Am I breaking rules doing it like this?
    t
    w
    • 3
    • 10
  • b

    bhatnagarm

    02/13/2020, 6:47 AM
    Hey everyone, A quick question regarding ViewModel injection using dagger. So as per my understanding we have generic factory class that Implements ViewProvder.factory interface and is responsible for creating ViewModel instance when demanded from Activity/Fragment. And whatever dependencies required by that ViewModel is fulfilled by dagger itself. But what if there is a dependency say Bundle that I would like to pass to my ViewModel during it's construction. So is that possible by doing some tweaks within custom ViewModelFactory.
    g
    • 2
    • 9
  • j

    Joan Colmenero

    03/10/2020, 11:27 PM
    In case anyone is bored, I'm posting a question on 😒tackoverflow: about dagger [1], I'm missing something but I'm not able to find it.. [1] : https://stackoverflow.com/questions/60627262/lateinit-property-androidinjector-has-not-been-initialized-dagger-2
    a
    • 2
    • 3
  • r

    ritesh

    03/11/2020, 7:41 PM
    Recently working on a project and followed modularization with clean architecture. db-module -> all db related stuff and dagger provider, the class with @Module annotated api-module -> all api related i/o's and dagger provider domain-module-> dependent on above 2 using
    impl
    not
    api
    as i dont want to trigger app-module build if any change in above to modules. And it has use cases and Dagger @Module class with above @Modules added (data and api) Something like this
    @Module(includes = [ApiModule::class, DatabaseModule::class])
    object AppModule
    app-module -> the ui layer, dependent on domain module using
    impl
    not api, and this module has Dagger components. Problem starts when dagger kicks in, whe dagger builds the graph it generated all the factories in the generated folder for providers in the sepecific modules like for ApiModule in its own and DatabaseModule in it's own and they are only exposed in domain layer and domain layer in app layer by impl. After compilation dagger throws AppComponent not found. The issue i found was it was not able to reach the generated factor classes from app-layer as app-layer is dependent on domain and domain on data and api-layer using
    impl
    not
    api
    and changin to
    api
    fixed by issue. But, i dont want to go this way, because if any changes in the outer layers (data and api) the build will also be trigerred for app-layer if exposed by api. I am thinking of keeping the all providers classes in the domain-layer. I think it will work. Am I breaking any rules or there is a better way to do it.
    m
    j
    • 3
    • 7
  • c

    Colton Idle

    03/13/2020, 9:10 AM
    I've read a lot that you can do the same thing that AAC ViewModels give you if you just use Dagger. So you don't need VMs! No one ever seems to give an example of how this works even though I would assume there's only really 1 technique to get it done? I feel like I understand the Activity lifecycle fairly well, but I don't understand how Dagger would know how to scope something like my MessagingActivity across config changes. To go even further, maybe your Activity is open in split screen, and then you have another app that shares into your app in the other split screen. Essentially giving you two messaging activities. At this point, I would assume that you would have two distinct Scopes from dagger since you have two distinct instances of your MessagingActivity. How would I tell dagger to scope to a single instance of an activity where it will also know to "stay alive" and "outlive" the activity during config change? That's the big benefit of a AAC VM and I don't know where to start.
    j
    • 2
    • 2
  • c

    Colton Idle

    03/14/2020, 2:25 PM
    I updated from dagger 2.21 to dagger 2.27 and now I see errors when compiling
    error: Dagger does not support injection into Kotlin objects
    I'm admittedly someone still very new to dagger and so I'm not sure if I'm violating some overarching DI rules with trying to inject my moshi instance into my "util object". Can someone point me in the right direction of a solution? I suppose I can write extension methods instead of having this java util that was converted to a kotlin object?
    p
    s
    j
    • 4
    • 21
  • a

    Ahmed Ibrahim

    03/15/2020, 7:42 PM
    Has anyone figured out a solution for the
    @JvmSuppressWildCard
    problem when injecting generic classes through Dagger? It is becoming too ugly for me 😞
    internal class SalesSectionReader @Inject constructor(
        private val sectionsLocalDataSource: SectionsDataSource,
        private val saleEntityToSaleSectionSaleMapper: Mapper<@JvmSuppressWildcards SaleEntity, @JvmSuppressWildcards SaleSection.Sale>,
        private val blogEntityToBlogSectionMapper: Mapper<@JvmSuppressWildcards BlogEntity, @JvmSuppressWildcards SaleSection.Blog>,
        private val tagEntityToSaleSectionTagMapper: Mapper<@JvmSuppressWildcards TagEntity, @JvmSuppressWildcards SaleSection.Tag>
    ) : StoreListReader<AllSectionsKey, SaleSection>
    j
    • 2
    • 3
  • c

    Colton Idle

    03/18/2020, 3:55 PM
    I'm learning Dagger and the biggest motivator behind learning it is to test deterministic responses from my backend. I'm following the typical Android arch guide, so yeah (I know I'm a bad person for using AAC VMs) Activity + Fragments + AAC VMs and a Repository. My "issue" is that it seems like I could just use Dagger to swap out Repository and FakeRepository and that would work... but it looks like I could also just use MockWebServer so I could mock the entire server interaction, as well as failures, etc etc. Does anyone have advice on to what route to go? My thinking that having a Repository and FakeRepository isn't actually all that helpful anymore and that MockWebServer from okhttp would actually be a ton better. In that case though... I don't think I would need Dagger at all? I'd love to be able to run my app in mock server mode though. Any advice would be appreciated. TLDR Which layer is the right one to fake stuff? VMs? Repository/FakeRepository? or real server and MockWebServer? Leaning MockWebServer
    w
    t
    g
    • 4
    • 11
  • c

    Colton Idle

    03/19/2020, 12:54 AM
    I was also curious about this. If DI is so important, I would think that many libraries would use DI internally. Is Dagger really meant for app level code and not libraries? I would expect something like Retrofit or OkHttp to use Dagger
    s
    j
    • 3
    • 7
Powered by Linen
Title
c

Colton Idle

03/19/2020, 12:54 AM
I was also curious about this. If DI is so important, I would think that many libraries would use DI internally. Is Dagger really meant for app level code and not libraries? I would expect something like Retrofit or OkHttp to use Dagger
s

streetsofboston

03/19/2020, 1:08 AM
If it's a library that is used internally only, part of your suite of apps, go ahead and use Dagger or anything you like. But for public libs, I'd suggest not using it (nor Koin, Kodein, etc). Try not to tie your libs users to a framework. However, make your library easy to use/configure with any DI library that the creators of apps could choose.
j

jw

03/19/2020, 1:31 AM
You can use Dagger in a library, you just shade it. It has a minimal runtime. You expose an interface that represents a component and then others can use it as a component dependency. Espresso does this, for example.
💯 2
c

Colton Idle

03/19/2020, 1:32 AM
Understood, but as I learn more about DI and it's importance, and how Dagger is used widely at square and such, why don't those libs use Dagger?
j

jw

03/19/2020, 1:32 AM
Well Retrofit and OkHttp still practice inversion of control. They don't really need Dagger
c

Colton Idle

03/19/2020, 1:35 AM
Okay. So it's mostly a "they don't need it" type of deal because they're small enough and they practice IOC, and if anything could do manual DI if they really need?
j

jw

03/19/2020, 1:35 AM
Yes. And also everything in the two are scoped to the Retrofit or OkHttpClient instance. They don't have scopes.
c

Colton Idle

03/19/2020, 1:37 AM
Thanks. That helps me in understanding when is the right time to introduce a DI framework like Dagger.
View count: 6