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
dagger
  • s

    Sagar Suri

    03/19/2020, 2:54 AM
    Question regarding the usage of
    @Singleton
    and
    @Inject
    inside the code instead of
    Module
    ? I have a personal opinion of creating
    Modules
    and defining all my dependencies there instead of marking classes with the above annotations? Reason being: 1. It help me understand the dependencies and configurations from a single file i.e
    Module
    . 2. It avoid mixing code with configuration(annotations). What are your opinion on this? I don’t prefer the following code:
    @Module
    class BookingDatabaseModule {
    
        @Provides
        fun provideBookingDao(database: BookingDatabase) = database.bookingDao()
    }
    Following is my preferred way of doing it:
    @Module
    class BookingDatabaseModule {
    
        @Provides
        @Singleton
        fun provideDatabase(context: Context) = BookingDatabase.newInstance(context)
        
        @Provides
        fun provideBookingDao(database: BookingDatabase) = database.bookingDao()
    }
    What are your opinions?
    i
    g
    c
    • 4
    • 18
  • i

    Ianmedeiros

    03/24/2020, 2:06 AM
    Is it possible to remove the ambiguity to provide a ListProcessor just by providing two distinct lists?
    Untitled.txt
    s
    g
    • 3
    • 12
  • c

    Colton Idle

    03/29/2020, 5:17 PM
    Since Dagger 2 supports incremental kapt, is there any benefit to using dagger-reflect?
    n
    g
    • 3
    • 5
  • s

    Slackbot

    04/14/2020, 5:06 AM
    This message was deleted.
    j
    • 2
    • 1
  • c

    Colton Idle

    04/24/2020, 12:51 AM
    I need two global OkHttp instances in my app. I'm a dagger noob, but I inherited a project that already has the single okhttp instance, but encountering problems when I try to add a second one. What's the defacto way to have two objects of the same type in the same scope?
    n
    • 2
    • 4
  • j

    Joan Colmenero

    04/30/2020, 11:12 AM
    Hello! I'm facing this error whenever I want to create UI tests with Espresso using Dagger
    java.lang.RuntimeException: android.app.Application does not implement dagger.android.HasAndroidInjector
    Any idea, why? It only happens with UI tests, the app runs and everything is injected correctly.
    j
    w
    f
    • 4
    • 7
  • a

    Archie

    05/19/2020, 11:08 AM
    Does anyone have a new about changes related to Dagger-Android?
    s
    j
    • 3
    • 3
  • r

    rkeazor

    05/20/2020, 1:14 AM
    Is it possible to @binds two different interfaces to the same instance and inject both to the same class?
    g
    g
    w
    • 4
    • 6
  • j

    Joan Colmenero

    05/20/2020, 3:21 PM
    I've posted a question some days ago and I'm still looking for a proper solution, the thing is that I'm trying to create a TestAppComponent because when creating UI tests and doing the call it's not using the mockWebServer is doing the real call, any help is appreciate: https://stackoverflow.com/questions/61539234/dagger2-not-injecting-instance-on-test
    w
    • 2
    • 17
  • j

    Joan Colmenero

    05/20/2020, 10:34 PM
    I appreciate help on this ^
    s
    • 2
    • 25
  • c

    Colton Idle

    05/27/2020, 3:26 AM
    Can anyone vouch for speeding up dagger via this snippet in gradle? The snippet seems to: Enable fastInit Disable formatGeneratedSource Enable incremental compilation (I'm using dagger 2.21 so incap isn't enabled automatically) https://github.com/google/dagger/issues/1120#issuecomment-493512366
    a
    g
    • 3
    • 11
  • c

    Colton Idle

    05/27/2020, 6:40 AM
    Reposting this question from March that didn't get any replies (except from Jake). Don't want to keep bothering one person. Can anyone chime in? I'm still learning dagger (did a big deep dive this past week) and I have a better grasp on it and components and subcomponents, etc, but I still don't understand the comments from people that say "If you use Dagger, you don't need AAC ViewModels". I would love to kill off AAC VM completely because I think the factory you need to create in order to pass in an argument is overkill and it seems like a properly scoped component would just be simpler in this case. (note: I also understand that this "hilt" thing is coming out soon, but I still would find this answer beneficial, even from a curiosity point of view. I'm trying to prevent someone from answering "Just wait till June 3rd")
    a
    s
    m
    • 4
    • 6
  • n

    Nicholas Doglio

    05/28/2020, 12:48 AM
    It appears 2.28 with an alpha for hilt was released but no changelog 👀
    👀 3
    g
    • 2
    • 2
  • c

    Colton Idle

    06/06/2020, 1:41 PM
    I have a really basic dagger setup in my android app. I basically just followed the dagger guide/tutorial and now I went to add dagger-reflect by Jake Wharton, but now my basic setup won't compile because the
    builder()
    method isn't available on MyAppComponent. Anyone have any ideas? The readme doesn't say that I need to change anything. Opened an issue here as well https://github.com/JakeWharton/dagger-reflect/issues/191 EDIT 1: I did find this issue (https://github.com/JakeWharton/dagger-reflect/issues/145) which seems similar, but it doesn't really have a solution? The last semi-helpful response there is to use
    @Component.Factory
    but I'm not sure how that helps. Android Dagger guide doesn't talk about that at all, which just makes it weird that dagger reflect doesn't work with a "typical"/basic dagger setup. EDIT 2: Also found this https://github.com/JakeWharton/dagger-reflect/issues/4 where Jake says "in general you should refactor to 
    @BindsInstance
     and stateless modules." Maybe that's my solution? But how do I move my simple setup to "BindsInstance and stateless modules". That's going wayy over my head. In the same comment JW seems to mention that Builder() should also already work? Sorry for being a dagger noob here
    p
    • 2
    • 5
  • c

    carlos cdmp

    06/08/2020, 11:59 AM
    Is there a way to make a property in an object to be injected from dagger as a lateinit property?
    g
    • 2
    • 1
  • c

    Colton Idle

    06/10/2020, 12:14 AM
    I have my appComponent that takes in an argument when I call
    .create()
    which is the url that my networkModule needs. java
    public interface AppComponent {
        @Component.Factory
        interface Factory {
            AppComponent create(@BindsInstance @Named("url") String url);
        }
    }
    This is my networkModule. kotlin
    @Module
    class NetworkModule @Inject constructor(@Named("url") val url: String) {...}
    I get this dagger error:
    error: @Component.Factory method is missing parameters for required modules or components: [com.myapp.internal.NetworkModule]
    Ideas? Looks like my BindsInstance should satisfy my networkModule.
    w
    • 2
    • 3
  • r

    rattleshirt

    06/11/2020, 11:37 AM
    Wrt Hilt: how does the
    @InstallIn
    work inside gradle submodules? Would you need a sub component per module? I couldn’t find anything in the official doc regarding this.
    j
    m
    w
    • 4
    • 21
  • t

    Thomas

    06/11/2020, 4:54 PM
    Is there a way to access the Fragment args when using Hilt? I tried something like this:
    @InstallIn(FragmentComponent::class)
    @Module
    object MyFragmentModule {
    
        @Provides
        @FragmentScope
        internal fun providesViewModel(
            fragment: MyFragment,
            anotherDependency: Dependency
        ) = MyViewModel(
            fragment.requireArguments().getString("argument"),
            anotherDependency
        )
    }
    
    @AndroidEntryPoint
    class MyFragment : Fragment() {
        // ...
    }
    However, this does not appear to work as it shows the following error when building:
    error: [Dagger/MissingBinding] com.myapp.MyFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
    Am I doing something wrong? This worked fine without Hilt when using Dagger Android.
    a
    j
    • 3
    • 13
  • m

    Marco Righini

    06/12/2020, 2:05 PM
    Hi! First thing, amazing work with Hilt 😉 Just two questions: • There are some situations in which you need to manually recreate the application dependencies graph and then inject the application again. Is there a way to do it with Hilt? ApplicationComponent is managed by the framework so it seems not. I mean, there’s a way to disable the automatic component creation and app injection in the @HiltAndroidApp and do it manually? • Let’s say I want to maintain the old dagger android way for the activities that I already have. How do I have to deal with AndroidSupportInjectionModule? It’s autogenerated so no way to add @InstallIn(ApplicationComponent::class) Side note: https://codelabs.developers.google.com/codelabs/android-dagger-to-hilt/index.html?index=..%2F..index#4 seems outdated
    m
    w
    m
    • 4
    • 13
  • a

    Archie

    06/13/2020, 2:57 PM
    Hi guys, I was wondering how to add
    FragmentFactory
    with Hilt. It seems that
    Hilt
    works almost the same way as
    dagger-android
    (please correct me if im wrong) and so, using
    FragmentFactory
    is really hard. Can anyone guide me please.
    e
    • 2
    • 2
  • a

    Archie

    06/14/2020, 9:06 AM
    What exactly is the difference between
    ActivityRetainedComponent
    vs
    ActivityComponent
    ??
    g
    • 2
    • 4
  • a

    Ahmed Ibrahim

    06/15/2020, 10:03 AM
    I'm wondering if anyone has started facing
    bindsMethod does not represent a type element
    issues when started migrating to Hilt? It never popped up before 😕
    Caused by: java.lang.IllegalArgumentException: bindsDateFormatter(com.example.date.SalesDateFormatter) does not represent a type element
            at dagger.shaded.auto.common.MoreElements$CastingElementVisitor.defaultAction(MoreElements.java:395)
            at dagger.shaded.auto.common.MoreElements$CastingElementVisitor.defaultAction(MoreElements.java:386)
            at com.sun.tools.javac.code.Symbol$MethodSymbol.accept(Symbol.java:1644)
            at dagger.shaded.auto.common.MoreElements.asType(MoreElements.java:128)
            at dagger.internal.codegen.validation.TypeCheckingProcessingStep.lambda$process$0(TypeCheckingProcessingStep.java:51)
            at com.google.common.collect.RegularImmutableMap.forEach(RegularImmutableMap.java:185)
            at dagger.internal.codegen.validation.TypeCheckingProcessingStep.process(TypeCheckingProcessingStep.java:48)
            at dagger.internal.codegen.ModuleProcessingStep.process(ModuleProcessingStep.java:104)
            at dagger.internal.codegen.ModuleProcessingStep.process(ModuleProcessingStep.java:59)
    And it is just bound using a simple
    @Binds
    @Binds
        abstract fun bindsDateFormatter(it: SalesDateFormatter): DateFormatter
    g
    a
    • 3
    • 9
  • d

    deviant

    06/15/2020, 1:07 PM
    hi guys! i'm trying to migrate from Koin to Hilt what is the best way to inject fields into the BaseViewModel? i have such structure: MyViewModel extends BaseViewModel extends ViewModel is it possible to inject directly into the fields/properties of BaseViewModel?
    a
    g
    c
    • 4
    • 8
  • m

    Manuel Vivo

    06/18/2020, 7:39 PM
    Example of how to make AssistedInject work with Hilt at the moment https://twitter.com/manuelvicnt/status/1273699171078475780
    👏 7
    g
    h
    a
    • 4
    • 3
  • r

    Rafal

    06/20/2020, 8:12 AM
    One of the downsides of a single binding key space is that it can be extra work to place restrictions on code usage (e.g. if one feature shouldn't use bindings from another feature). For this we generally recommend using qualifier annotations that are restricted visibility or using an SPI plugin to enforce separation of code.
    I can’t find any info about this SPI plugin. Can anyone point me where I can read about this?
    a
    • 2
    • 2
  • m

    Mikael Alfredsson

    06/20/2020, 9:06 AM
    I have a module containing
    @Provides
        @Singleton
        fun providesMessageCenter(): MessageCenter = MessageCenter()
    for me, this seems to be quite unnecessary and I guess I could annotate the
    MessageCenter
    class directly instead to get it into the graph. Whats the best way of doing this (or is the best way to keep it as it is?)
    a
    • 2
    • 4
  • g

    gumil

    06/20/2020, 4:58 PM
    Hello people, in hilt is there a way to differentiate modules to be installed in specific entrypoints only?
    a
    r
    • 3
    • 5
  • d

    deviant

    06/23/2020, 12:53 PM
    is it possible to inject ViewModel into another ViewModel with Hilt?
    m
    • 2
    • 1
  • k

    KayCee

    06/29/2020, 4:42 AM
    I am trying to inject singleton Media Player instance to use in my 3 View Pager fragments. The injection seem works, I can use instance of Media Player in different fragments, but it is not singleton. The key thing is when I play music in a fragment, switch to another view pager fragment -> play music there -> it should stop the current music and play the one I choose.
    @Provides
        @Singleton
        fun provideMediaPlayer(): MediaPlayer {
            return MediaPlayer.create(applicationContext, R.raw.sample)
        }
    
    //AppComponent
    @Component(modules = [AppModule::class])
    @Singleton
    interface AppComponent {
        fun inject(activity: MainMusicActivity)
    
        fun inject(fragment: FeaturedFragment)
    
        fun inject(fragment: MyMusicFragment)
    }
    This is inject in fragment, I try both @Inject and @Inject set
    @Inject
        lateinit var mediaPlayer: MediaPlayer
    My question is am I using dagger correctly? Or is there any better way for getting singleton instance of media player with these view pager fragments
    j
    a
    • 3
    • 2
  • r

    Rafal

    07/03/2020, 2:20 PM
    Hi! TIL where you are using hilt there is new
    FragmentContextWrapper
    so calling any
    .context
    on any view that is in the fragment returns
    FragmentContextWrapper
    instead of an
    Activity
    . We have a
    Context
    extension:
    fun Context.navigateWithDirections(
        navDirections: NavDirections,
        navOptions: NavOptions? = NavOptions.Builder()
            .setEnterAnim(R.anim.nav_default_enter_anim)
            .setExitAnim(R.anim.nav_default_exit_anim)
            .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
            .setPopExitAnim(R.anim.nav_default_pop_exit_anim)
            .build()
    ) {
        (this as? Activity)?.findNavController(R.id.nav_host_fragment)?.navigate(navDirections, navOptions)
    }
    and this
    (this as? Activity)?
    check doesn’t pass cause there is
    FragmentContextWrapper
    . In the docs I see
    * Do not use except in Hilt generated code!
    So my question is. Is there any other way I can get the activity context instead of this wrapper?
    s
    j
    h
    • 4
    • 3
Powered by Linen
Title
r

Rafal

07/03/2020, 2:20 PM
Hi! TIL where you are using hilt there is new
FragmentContextWrapper
so calling any
.context
on any view that is in the fragment returns
FragmentContextWrapper
instead of an
Activity
. We have a
Context
extension:
fun Context.navigateWithDirections(
    navDirections: NavDirections,
    navOptions: NavOptions? = NavOptions.Builder()
        .setEnterAnim(R.anim.nav_default_enter_anim)
        .setExitAnim(R.anim.nav_default_exit_anim)
        .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
        .setPopExitAnim(R.anim.nav_default_pop_exit_anim)
        .build()
) {
    (this as? Activity)?.findNavController(R.id.nav_host_fragment)?.navigate(navDirections, navOptions)
}
and this
(this as? Activity)?
check doesn’t pass cause there is
FragmentContextWrapper
. In the docs I see
* Do not use except in Hilt generated code!
So my question is. Is there any other way I can get the activity context instead of this wrapper?
s

streetsofboston

07/03/2020, 2:27 PM
Not sure if there is already one such method, but you can traverse up the Context chain by repeatedly calling
.baseContext
(if that is the correct name) until that context
is Activity
.
j

jw

07/03/2020, 3:55 PM
It was never guaranteed to return the activity in the first place. Things like an
android:theme
attribute or simply using a
ContextWrapper
in a view before inflating children would break that assumption. You've always needed to perform a walk up the context hierarchy for accurate results, and you may never even reach an activity if the view is hosted in something like a floating window.
👍 1
h

harry.singh

07/03/2020, 4:21 PM
Is this true for both
getContext()
and
getActivity()
in a fragment?
View count: 4