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
  • h

    harry.singh

    07/03/2020, 5:05 PM
    Hey! In efforts to providing a single instance of
    Retrofit
    for my application, I'm using the
    Singleton
    scope in my network module which is then included in the
    ApplicationComponent
    with the same
    Singleton
    scope. But in order to do that I've to add network dependencies to my
    app
    module too. Is it possible to keep my retrofit instance singleton across application without adding network dependencies in my app module?
    g
    • 2
    • 2
  • j

    Jovan

    07/06/2020, 11:55 AM
    Hi everyone, just wanted to check what do you think, is Hilt safe for production?
    r
    • 2
    • 2
  • d

    Daniel

    07/10/2020, 6:46 PM
    Hey everyone, You can check out my project where I used dagger hilt with dynamic feature modules
    👏 5
    m
    • 2
    • 2
  • c

    Christian Maier

    07/16/2020, 6:09 PM
    Hi everyone, Let’s say I start an activity with some bundled data that I’d need way back in the repository. How can I provide that data using Hilt instead of passing it through several ${place_arch_pattern}-components? How do you solve problems like that?
    g
    • 2
    • 6
  • c

    Colton Idle

    07/20/2020, 12:53 AM
    Learning more about dagger and I want to sanity check how plausible this sounds. I really want to simplify my app with dependencies and components/scopes. I think I want to have 3 scopes defined. 1. Application scope 2. Logged In User scope 3. Logged Out User scope So in my head I'll have 3 components ApplicationComponent, LoggedInComponent, and LoggedOutComponent. How does that sound at a high level? I feel like it will solve 90% of my problems for me and it'll give me a chance to learn about scopes/components, provides/modules, and how to actually wire that up into my fragments/activities/all other classes.
    g
    d
    • 3
    • 12
  • m

    miqbaldc

    07/26/2020, 9:15 PM
    Is there any alternatives ways to provides a
    viewModelScope
    ? Moved to this issue instead with more details and examples: https://github.com/google/dagger/issues/2004
    g
    • 2
    • 11
  • c

    Colton Idle

    07/29/2020, 5:53 PM
    What is it called when my Component exposes some type via a field? Aka, instead of using field injection in Android, I can do X instead. I want to call them provision methods... but that sounds weird? Is that what people say when talking on a team? https://dagger.dev/api/latest/dagger/Component.html#provision-methods
    s
    j
    • 3
    • 4
  • k

    Kulwinder Singh

    07/30/2020, 10:15 AM
    How to provide arguments like this
    Callback
    in Fragment using HILT
    class PostAdapter @Inject constructor(
        @ApplicationContext private val context: Context,
        private val callback: Callback //HOW THIS CAN BE PROVIDED FROM FRAGMENT
    ) : ListAdapter<Post, PostAdapter.Holder>(DIFF) {
    
      /.../
    
       interface Callback {
            fun onClick(post: Post)
        }
    
    }
    r
    j
    +2
    • 5
    • 25
  • k

    Kulwinder Singh

    07/30/2020, 10:23 AM
    i mean how i can
    @Inject PostAdapter
    in any fragment ?
    r
    • 2
    • 3
  • h

    Horv

    07/30/2020, 11:41 AM
    I'm about to try HILT for my project. But as soon as I try to add the gradle plugin (even adding the classpath to dependencies) I'm getting errors all over my gradle file. I'm using Kotlin-syntax for my build.gradle-files. Would that be a problem?
    g
    • 2
    • 6
  • t

    trevjones

    07/30/2020, 3:38 PM
    is it just me or is
    @InstallIn
    violating inversion of control? if not for the abstract concept of the monolithic component hierarchy creating a dependency inversion boundary it would be cyclic in nature 😕
    j
    • 2
    • 4
  • a

    allan.conda

    07/31/2020, 5:05 AM
    Anyone here tried to benchmark build times after migrating to Hilt? I tried migrating a project, but the benchmarks show Hilt is significantly slower. I’m going to investigate if there’s just something wrong with my setup; and I’d love to hear your experiences if anyone can share 🙏
    c
    r
    +2
    • 5
    • 8
  • c

    Colton Idle

    07/31/2020, 6:59 AM
    Working on some best practices documentation for my team. Poll Do you prefer: 1️⃣ field injection 2️⃣ provision methods (
    @Provides
    )
    🤔 3
    2️⃣ 4
    1️⃣ 4
    w
    r
    +2
    • 5
    • 10
  • j

    Jeevan Deep Singh

    07/31/2020, 10:03 AM
    Hi, How can I implement dagger hilt in my module if my module is shipped as an aar library in the main project? Because I have to annotate my application class with @HiltApplication. How will this work for my library module?
    t
    • 2
    • 1
  • a

    Archie

    08/07/2020, 8:54 AM
    Hi Guys, may I ask a question. I am using
    Hilt
    for Android DI. I am wondering whats the recommended approach of where to define the
    Hilt
    Modules. In a multi-module project, is it ok to define
    Hilt
    modules in each module? So for example I have a
    UserModule (Android Submodule)
    and with in it I define the
    Hilt
    Module. Or is it better to define all
    Hilt
    Modules inside the
    app
    Module itself?
    r
    d
    • 3
    • 7
  • m

    myanmarking

    08/07/2020, 10:09 AM
    interface Builder
    class BuilderImpl @Inject(abstraction: Builder::class.java) constructor(): Builder
    j
    w
    • 3
    • 12
  • m

    Marcin Środa

    08/20/2020, 4:48 PM
    Hi guys, Looks I found some weird issue in Hilt. Try to create a sample activity with
    @AndroidEntryPoint
    in
    case
    package (
    com.android.ui.case
    or something). Result:
    Failed Caused by: javassist.NotFoundException:
    Are there any forbidden package names? (code without hilt annotation is working fine)
    f
    g
    • 3
    • 3
  • m

    Mohamed Ibrahim

    08/24/2020, 3:20 PM
    how to use Hilt with Dagger/Android for example AndroidInjector side by side
    g
    • 2
    • 3
  • a

    Archie

    08/25/2020, 12:11 PM
    It is normal that a dependency in one module needs to also be added to the main module when using hilt? I have a class in a module which uses a library:
    @AndroidEntryPoint
    class MyFragment: Fragment(), SomeInterfaceFromALibrary {
        @Inject
        lateinit var someClass: SomeClass
        
        ....
    }
    Now whenenver I build my project it says "could not access SomeInterfaceFromALibrary" The only way I fixed it was to add the same dependency in the main module:
    :app
    ...
    dependencies {
        implementation "someLibrary:version"
    }
    
    :otherModule
    ...
    dependencies {
        implementation "someLibrary:version"
    }
    Is this intended or am I doing something wrong?
    j
    • 2
    • 8
  • b

    bodo

    09/09/2020, 1:38 PM
    thanks for the quick response. i tried it with optional but with hilt it throws a compilation error: java.util.Optional<androidx.fragment.app.Fragment> cannot be provided without an @Inject constructor or an @Provides-annotated method.
    d
    • 2
    • 2
  • a

    Archie

    09/14/2020, 10:11 AM
    In Hilt is there a way to have a dependency scoped to
    @ActivityRetainedScoped
    but have a value injected to it from the
    Activity
    . I need the depedency to survive device rotation but the problem is it also needs a value taken from the `Activity`'s bundle. Any advise on how to work around this?
    a
    • 2
    • 11
  • a

    Ahmed Ibrahim

    09/25/2020, 11:54 AM
    I have several test classes that are annotated by
    HiltAndroidTest
    and they have
    UninstallModules
    with the same set of modules to uninstall. If I add or remove an extra module to uninstall, I have to cascade the changes to the rest. Is there a way to avoid repeating myself with Hilt or do I need to file a feature request for that? What I tried and didn't work (inspired by Spring Boot TestComponent annotation)
    @UninstallModules(SearchModule::class, SearchResultsModule::class, DestinationsSearchModule::class)
    @HiltAndroidTest
    internal class MonthsFragmentTest
    Tried writing an annotation that combines them
    @UninstallModules(
        SearchModule::class,
        SearchResultsModule::class,
        DestinationsSearchModule::class
    )
    @kotlin.annotation.Target
    annotation class UninstallSearchProductionModules
    and tried replacing them
    @UninstallSearchProductionModules
    @HiltAndroidTest
    internal class MonthsFragmentTest
    a
    • 2
    • 2
  • c

    Colton Idle

    10/02/2020, 3:47 AM
    Finally wrote out my thoughts about what makes Dagger useful from a "beginners" perspective. https://medium.com/@ColtonIdle/dagger-2-a-beginners-journey-to-understanding-why-dagger-is-useful-accdc0b42b63
    r
    p
    • 3
    • 4
  • p

    Pete Doyle

    10/08/2020, 3:04 AM
    (Pretty sure the answer is no, but wanted to double-check https://dagger.dev/hilt/migration-guide.html#be-aware-of-differences-with-monolithic-components) In Dagger-Android,
    @ContributesAndroidInjector
    made it easy to have a module that is scoped to a specific Activity/Fragment, i.e.:
    --- AppComponent:
    
    @Singleton
    @Component(
        modules = [
            ActivityBindingModule::class,
            AndroidSupportInjectionModule::class,
            // ...
        ]
    )
    interface AppComponent : AndroidInjector<MyApplication> {
        // ...
    }
    
    
    --- ActivityBindingModule:
    
    @Module
    internal abstract class ActivityBindingModule {
        @ActivityScope
        @ContributesAndroidInjector(modules = [MainActivityModule::class]) // MainActivityModule scoped to MainActivity
        internal abstract fun mainActivity(): MainActivity
    
        @ActivityScope
        @ContributesAndroidInjector(modules = [AnotherActivityModule::class]) // AnotherActivityModule scoped to AnotherActivity
        internal abstract fun anotherActivity(): AnotherActivity
    }
    
    
    --- MainActivityModule:
    
    @Module
    abstract class MainActivityModule {
    
        @FragmentScope
        @ContributesAndroidInjector(modules = [SignInFragmentModule::class])
        internal abstract fun signInFragment(): SignInFragment
    
        @FragmentScope
        @ContributesAndroidInjector
        internal abstract fun whatsNewFragment(): WhatsNewFragment
    
        @FragmentScope
        @ContributesAndroidInjector
        internal abstract fun settingsFragment(): SettingsFragment
    }
    Is something similar possible in HIlt? Or is there another strategy that might be similar? (random: if not, maybe in It seems like MainActivityModule and AnotherActivityModule would both use
    @InstallIn(ActivityScoped::class)
    , then both MainActivity and AnotherActivity could
    @Inject
    from either (I might be missing something?). Similarly, is it possible to have a setup where Fragments could
    @Inject
    things from their host Activity’s module? (e.g. in the above example, SignInFragment could inject anything from AppComponent, MainActivityModule, and SignInFragmentModule. We’ve taken advantage of this property of Dagger-Android, and I’m currently not quite sure what a migration to Hilt would look like.
    a
    b
    • 3
    • 6
  • b

    Bacho Kurtanidze

    10/12/2020, 9:09 AM
    In my project I have LoadingHandler class which is responsible for showing different kind of progress bars. I want to inject it in my fragments and attach its lifecycle to fragments view so I use ViewWithFragmentComponent but when I build my project it crashes with error which is telling me that LoadingHandler couldn't be provided. which is weird cause when I change ViewWithFragmentComponent to just FragmentComponent it works fine am I missing something?
    a
    • 2
    • 1
  • m

    Miguel Coleto

    10/13/2020, 7:03 PM
    Using dagger for the first time I have a doubt coming from Koin. I have a viewmodel which requires a param by constructor:
    class UserDetailsViewModel(private val userId: String) : ViewModel() { ... }
    With Koin I could inject it in my fragment/activity like this:
    class UserDetailsFragment : Fragment() {
      private val viewModel: UserDetailsViewModel by lifecycleScope.viewModel(parametersOf(
        requireArguments().getString(USER_ID)
      ))
    }
    How can I achieve this with Dagger/Hilt?
    a
    j
    • 3
    • 4
  • s

    Shawn Witte

    10/14/2020, 9:37 PM
    Is there a way to use
    @Inject
    on a Kotlin
    object
    or are my only options to convert it to a
    class
    or use
    @Provides
    ?
    ➕ 1
    c
    t
    • 3
    • 3
  • j

    Jeremy

    10/21/2020, 1:44 AM
    When utilizing subcomponents keep getting error
    java.lang.reflect.InvocationTargetException (no error message)
    . Is there any way to expand upon that to see what the actual issue is?
    c
    • 2
    • 3
  • p

    pollux-

    10/26/2020, 7:10 PM
    I'm using Dagger @Binds to binding the interface to implementation. I have genric mapper which transform one object to other.
    interface DataMapper<T, R> {
         fun transform(from: T): R
     }
    So I have couple of Data mapper in each use case layer . Let's I have something like this
    class AccountDataMapper @Inject constructor():
    DataMapper<Account,Result<Account>>{
    override fun transform(account : Account){
    }
    }
    How can I bind this. I have many mapper in the like Login Mapper,User mapper. When I use thr binder it's complaining that @Binds method parameter type must be assignable to the return type @Binds
    abstract fun bindAccountMapper(mapper AccountDataMapper) : DataMapper<Account,Result<Account>>
    Thanks in advance
    r
    • 2
    • 2
  • b

    blakelee

    10/28/2020, 4:48 AM
    Is there way to inject viewmodels without having to create a factory for each one and also without hilt? I don’t need savedStateHandle or anything, I just want to use it like @Inject but have it survive configuration changes that a normal class won’t survive. I’ve seen several medium articles but I haven’t found a solution that can do it without a factory or hilt
    a
    a
    • 3
    • 9
Powered by Linen
Title
b

blakelee

10/28/2020, 4:48 AM
Is there way to inject viewmodels without having to create a factory for each one and also without hilt? I don’t need savedStateHandle or anything, I just want to use it like @Inject but have it survive configuration changes that a normal class won’t survive. I’ve seen several medium articles but I haven’t found a solution that can do it without a factory or hilt
a

allan.conda

10/28/2020, 7:10 AM
@Binds
@IntoMap @ViewModelClassKey(LoginViewModel::class)
abstract fun bindViewModel(viewModel: SomeViewModel): ViewModel
look for tutorials involving ViewModelClassKey
a

Ahmed Ibrahim

10/28/2020, 9:46 AM
Yes, there is, since you don't use SavedStateHandle you can do it by using a Provider.
@Inject
lateinit var viewModelProvider: Provider<MyViewModel>

private val myViewModel by viewModels {
    viewModelProvider.get()
}
b

blakelee

10/29/2020, 1:41 AM
@allan.conda That just replaces the factory with a binds @Ahmed Ibrahim The viewModelProvider.get() doesn't seem to work. viewModels wants a ViewModelProvider.Factory
a

allan.conda

10/29/2020, 1:41 AM
Yeah… you said no Factory or Hilt… That’s the plain Dagger solution
b

blakelee

10/29/2020, 1:43 AM
I was hoping there was a way to set it up with just @Inject like many of my other classes. I thought there was a way to do it similar to what Ahmed was suggesting, but I must be mistaken.
a

allan.conda

10/29/2020, 1:45 AM
using Hilt is the closest to what you’re looking for with
@ViewModelInject
otherwise there’s no easy way since ViewModels are a corner case,
a

Ahmed Ibrahim

10/29/2020, 8:54 AM
@blakelee Hey, sorry for providing an incomplete code, but yeah it's missing the ViewModelProvider.Factory as you said, but you can get around that by doing
@Inject
    lateinit var viewModelProvider: Provider<MyViewModel>

    private val myViewModel: MyViewModel by viewModels {
        object: ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                @Suppress("UNCHECKED_CAST")
                return viewModelProvider.get() as T
            }
        }
    }
Now you can replace the ugly
object: ViewModelProvider.Factory
part by extracting it to an inline function to get a much more elegant version of the above code
@Inject
    lateinit var viewModelProvider: Provider<ViewModel>

    private val myViewModel: ViewModel by viewModels {
       createSimpleViewModelFactory {        viewModelProvider.get() 
}
    }
b

blakelee

10/29/2020, 6:32 PM
@Ahmed Ibrahim This seems like it could work. It's running on my device just fine. Just gotta make sure it really does handle config changes. Thanks!
View count: 6