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

    Hovhannes

    08/20/2021, 1:44 PM
    Hello, I've a difficult question. I use Hilt. I get  this error   'java.lang.IllegalArgumentException: SavedStateProvider with the given key is already registered'. What is the reason?
    Fragment
    private var instance: LoginFragment? = null
     private val viewModel by viewModels<AuthViewModel>()
     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            binding = FragmentLoginBinding.bind(view)
            instance =this
    }
    
    fun login(): String {
        viewModel.login(clientId, partner.toString(), password)
        val clientId = binding.editTextTextEmailAddress.text.toString().trim()
    
        val encrypted = encrypt(clientId, publicKey)
      
        return encrypted
    }
    RemoteDataSource
    private fun getRetrofitClient(): OkHttpClient {
    
        val str= LoginFragment().getInstance()?.login()
    ....
    g
    s
    • 3
    • 2
  • r

    rkeazor

    09/04/2021, 11:17 AM
    Hey DaggerHeads, im running into a issue where hilt doesn't allow BaseClasses with default values. For Example
    abstract class BaseActivity(layouId: Int = 0) // Hilt complains that default value of 0 is not allowed
    ➕ 1
    f
    • 2
    • 5
  • c

    Colton Idle

    09/17/2021, 10:27 AM
    Why isn't it necessary to write @InstallIn on a class that you own and only on a module? i.e. I expected this to work
    @Singleton
    @InstallIn(Singleton::class)
    class MyRepo @Inject constructor(val myManager: MyManager) :
    j
    • 2
    • 1
  • d

    dave08

    09/19/2021, 6:39 AM
    Is there a way to inject a
    value class
    with Dagger2? It seems like it's not working... (don't think it makes a difference, but I'm using Anvil with it...)
    e
    • 2
    • 3
  • h

    Hovhannes

    09/24/2021, 10:44 AM
    Hello, I've a question. Why Android Studio shows "Class "App" is never used" this warning when I use Koin? Using Hilt it doesn't show this warning. As you see that I used 'App' in Manifest.
    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    class App : Application(){
        override fun onCreate() {
            super.onCreate()
            startKoin {
                androidContext(this@App)
                modules(listOf(appModule, repoModule, viewModelModule))
            }
        }
    }
    s
    • 2
    • 1
  • e

    enighma

    09/27/2021, 11:04 PM
    Update 2:
    @JvmSuppressWildcards
    Adding that to the constructor injection site did the trick. @ephemient thank you! 🙂 Update 1: In my use-case below
    MyType
    was a sealed class, which is what caused the issue. Original message: I think this question applies here even though I'm using hilt: I have a provider function that provides a kotlinflow like so:
    fun provideX(): Flow<MyType>
    However, when I try to compile I get "cannot be provided without an @Provides-annotated method". I'm guessing it wants a provider for MyType? I'm not sure, because it seems to work if it's:
    fun provideX(): Flow<Long>
    I guess in general, are there any recommendation around flows/async together with dagger/hilt?
    e
    • 2
    • 3
  • g

    Geert

    09/28/2021, 1:02 PM
    I have an error with hilt, i dont know why. I keep getting the error:
    java.lang.RuntimeException: Cannot create an instance of class app.medxpert.pgo.compose.privacy_agreement.PrivacyAgreementViewModel
    The Preferences:
    class Preferences @Inject constructor(
        @ApplicationContext val context: Context
    ) {...}
    My ViewModel:
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewModelScope
    import dagger.hilt.android.lifecycle.HiltViewModel
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.launch
    import javax.inject.Inject
    
    @HiltViewModel
    class PrivacyAgreementViewModel @Inject constructor(
        private val sharedPrefs: Preferences,
    ) : ViewModel() {...}
    How I call it:
    @Composable
    fun PrivacyAgreementView(
        viewModel: PrivacyAgreementViewModel = hiltViewModel()
    ) {
    What could be wrong?
    f
    • 2
    • 3
  • h

    Hovhannes

    10/01/2021, 5:59 AM
    Hello, I've a question. I get this error, but I can't understand it. How can I fix it?  Thanks in advance.  "[Dagger/MissingBinding] @javax.inject.Named("vbttop") retrofit2.Retrofit cannot be provided without an @Provides-annotated method.   public abstract static class SingletonC implements App_GeneratedInjector,                          ^       @javax.inject.Named("vbttop") retrofit2.Retrofit is injected at           com.example.alwayson.di.NetworkModule.provideApiVbtop(retrofit)       com.example.alwayson.data.VbtopApi is injected at           com.example.alwayson.repository.VbtopRepository(vbtopApi)       com.example.alwayson.repository.VbtopRepository is injected at           com.example.alwayson.viewModel.MainVieModel(�, vbtopRepository, �)"
    @Module
    @InstallIn(SingletonComponent::class)
    class NetworkModule {
    
    
        @Provides
        fun provideBuildlogger(): HttpLoggingInterceptor {
            return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        }
    
    
        @Provides
        @Singleton
        fun provideOkHttpClient() = if (BuildConfig.DEBUG) {
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
            OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build()
        } else {
            OkHttpClient
                .Builder()
                .build()
        }
    
    
        @Provides
        @Singleton
        @Named("base")
        fun provideRetrofitBuilder(
              alwaysonUrl: String, okHttpClient: OkHttpClient
        ): Retrofit {
            return Retrofit.Builder()
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .baseUrl(alwaysonUrl)
                .client(okHttpClient)
                .build()
        }
    
    
        @Provides
        @Singleton
        @Named("vbtop")
    
        fun provideRetrofitBuilderVbttop(
            @Named("vbttop") vbttopUrl: String, okHttpClient: OkHttpClient
        ): Retrofit {
            return Retrofit.Builder()
                .addConverterFactory(MoshiConverterFactory.create())
                .baseUrl(vbttopUrl)
                .client(okHttpClient)
                .build()
        }
    
    
        @Provides
        @Singleton
        fun provideApi(@Named("base") retrofit: Retrofit): UrlApi {
            return retrofit.create(UrlApi::class.java)
        }
    
    
        @Provides
        @Singleton
        fun provideApiVbtop(@Named("vbttop") retrofit: Retrofit): VbtopApi {
            return retrofit.create(VbtopApi::class.java)
        }
    
    
        @Provides
        fun provideBase() = BuildConfig.BASE_URL
    
        @Provides
        @Named("vbttop")
        fun vbttopUrl(): String = ""
    }
    interface UrlApi {
        @GET
        suspend fun getUrls(@Url path: String): Response<JsonData>
       
    }
    interface VbtopApi {
        @GET
        suspend fun getVbtop(@Url url:String): Response<VbtopUrl>
    }
    class MainRepository @Inject constructor(private  val urlApi: UrlApi, private  val vbtopApi: VbtopApi) {
        suspend fun getUrls(path:String) = urlApi.getUrls(path)
    
        suspend fun getVbtop(url:String)=vbtopApi.getVbtop(url)
    
    }
    e
    r
    • 3
    • 6
  • r

    Ravin Jain

    10/08/2021, 1:12 AM
    How to provide 
    viewModelScope
     as a constructor injection through hilt to other classes which are 
    viewmodelscoped
    f
    • 2
    • 2
  • r

    rkeazor

    10/09/2021, 1:59 PM
    Hey if you have a base Activity that is using dagger , and your migrating to hilt, is there a incremental way to handle changing it ? also do both BaseActivity and the class inherting it need to be annontated with @AndroidEntryPoint when using hilt ? Assuming your also using hilt in the base activity
    f
    • 2
    • 1
  • s

    Slackbot

    10/13/2021, 9:32 AM
    This message was deleted.
    m
    • 2
    • 1
  • s

    Slackbot

    10/20/2021, 11:59 AM
    This message was deleted.
    c
    • 2
    • 1
  • m

    Mikołaj Karwowski

    10/25/2021, 9:59 AM
    I tried creating a pure Kotlin/Gradle project in Intellij to play around with dagger (currently losing my mind over it lol) But even with very simple module/component it's not working as soon as I add a simple @provides or @binds annotation inside the module I get something along the lines of:
    [kapt] di.HeaterModule: Can't reference type 'Heater' from default package in Java stub.
    as a warning and the error is:
    error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    public abstract interface HeaterModule {
    To be clear, this is my module:
    @Module
    interface HeaterModule {
    
        //Tried both
    //    @Binds
    //    fun bindHeater(heater: SmallHeater): Heater
        
        @Provides
        fun provideHeater(): Heater {
            return SmallHeater()
        }
    }
    The component that doesn't even do anything:
    @Component(modules = [HeaterModule::class])
    interface TeaComponent{
    //    fun teaMaker(): TeaMaker
    }
    And the cherry on the top where I suspect the errors to be, but can't find them i.e.
    build.gradle.kts
    file:
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    plugins {
        kotlin("kapt") version "1.5.31"
        kotlin("jvm") version "1.5.10"
        application
    }
    
    group = "me.mkarwowski"
    version = "1.0-SNAPSHOT"
    
    kapt {
        generateStubs = true
        keepJavacAnnotationProcessors = true
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation( "com.google.dagger:dagger:2.39.1")
        annotationProcessor( "com.google.dagger:dagger-compiler:2.39.1")
        kapt( "com.google.dagger:dagger-compiler:2.39.1")
    
        testImplementation(kotlin("test"))
    }
    
    tasks.test {
        useJUnit()
    }
    
    tasks.withType<KotlinCompile>() {
        kotlinOptions.jvmTarget = "1.8"
    }
    
    application {
        mainClass.set("MainKt")
    }
    Am I doing anything obviously wrong here? I'll upload it to github in a second so You can reproduce it
    w
    c
    • 3
    • 5
  • c

    Chris Fillmore

    10/27/2021, 12:39 AM
    Is there a way to bind a dependency twice? Once in SingletonComponent, once in ActivityComponent? In my use case I have two instances of a dependency: once in an Activity and once in a Service. The dependency itself depends on a
    Context
    , so I want to use the Activity context where possible. I suppose I could accomplish this binding with annotations, but I was wondering if there was another way.
    ➕ 1
    f
    w
    • 3
    • 3
  • s

    Sanendak

    11/01/2021, 4:51 PM
    Hello everyone! I want to create library, but already using Hilt in lib classes. Q: How to create library that doesn't need Hilt/Dagger from other developers? Hilt needs Application class and that is the main problem.
    a
    • 2
    • 3
  • u

    ursus

    11/12/2021, 12:54 AM
    Is there a way to make dagger inject a
    value class Id(value: String)
    ? it complains that it doesnt see a provider for the underlying string value
    e
    • 2
    • 3
  • c

    Colton Idle

    11/14/2021, 6:25 PM
    I have a RepositoryActual and RepositoryInterface. I want to use RepositoryInterface at all of my call sites, but I want RepositoryActual to be created. Do I need to use a @Provides method, or can I do this with an @Inject annotation? (basically trying to see if I can spare myself having to create a @Module)
    p
    • 2
    • 8
  • g

    Geert

    11/15/2021, 10:28 AM
    Is it possible to provide a variable with hilt like an accesstoken? I receive it after logging in in the app, so basically I would provide an object with hilt and change the properties? But is that working?
    j
    u
    f
    • 4
    • 5
  • m

    mattinger

    11/18/2021, 1:42 PM
    For anyone using hilt, our app has a really big graph at the moment (a ton of modules). We’re considering using hilt in our libraries first, and would need to get objects from our existing component into the SingletonComponent. I tried creating a bridge module which would pull from our singleton components’ holder to get the objects. However, it seems when i switch from the dagger to the hilt compiler, it’s not generating my existing components. If i have both, i get an error that it can’t find some MemoizedSentinal internal class. Has anyone even tried this before? We’re just not ready for a big bang yet on our singleton component.
    t
    u
    • 3
    • 2
  • k

    K Merle

    11/24/2021, 7:46 AM
    Anyone doing hilt android tests with compose? I am following official guide, but I am having trouble implementing it. More specifically, current I am having an issue with objects that are annotated with
    @ViewModelScope
    or are installed in
    @ViewModelComponent
    .
    c
    • 2
    • 2
  • c

    Colton Idle

    11/27/2021, 7:20 PM
    Let's say I'm starting a new application and I have a
    CrashReporterService
    interface, and a real impl called
    FirebaseCrashReporterService
    . Both the interface and impl are on the Dependency graph, and so... nothing prevents someone from Injecting FirebaseCrashReporterService. Is there anything I can do to hide my real impls so that people only use the interface?
    n
    j
    +2
    • 5
    • 20
  • c

    Colton Idle

    12/01/2021, 6:31 PM
    In an attempt to hide concrete classes you don't want your team to accidentally use. Which option would you go for? Interface and concrete:
    interface CrashReporterService {
      fun logFatal(e: Exception)
    }
    
    class FirebaseCrashReporterService : CrashReporterService {
      override fun logFatal(e: Exception) {
        // do something
      }
    }
    Option 1️⃣ :(dont add the concrete to nav graph and just create it at the Provider)
    @Module
    object FirebaseCrashReporterModule {
        
        @JvmStatic
        @Provides
        fun firebaseCrashReporter(dependencies..) : CrashReporter {
            return FirebaseCrashReporter(...)
        }
    }
    Option 2️⃣: (use a qualifier to make the type "harder" to accidentally use)
    @Module
    @InstallIn(SingletonComponent::class)
    abstract class AppInterfaceModule {
      @Singleton
      @Binds
      abstract fun bindsCrashReporterService(
          @Named("placeholder_qualifier") service: FirebaseCrashReporterService
      ): CrashReporterService
    }
    
    @Module
    @InstallIn(SingletonComponent::class)
    class AppImplModule {
      @Singleton
      @Provides
      @Named("placeholder_qualifier")
      fun bindsCrashReporterService(): FirebaseCrashReporterService {
        return FirebaseCrashReporterService()
      }
    }
    2️⃣ 1
    1️⃣ 5
    a
    u
    • 3
    • 4
  • b

    blakelee

    12/06/2021, 8:01 PM
    Is it possible to have fragment scoped custom providers for viewmodels? Here is what I currently have to do: • I create my custom object
    @Module
    @InstallIn(FragmentComponent::class)
    object FragmentModule {
        @Provides
        @FragmentScoped
        fun provideMyObject(fragment: Fragment): MyObject {
            return fragment.getMyObject() // I can only get this from a fragment
        }
    }
    • I create my ViewModel without
    @HiltViewModel
    but with
    @Inject constructor
    • In my fragment I inject it with assisted inject
    @Inject
    lateinit var provider: Provider<MyViewModel>
    
    private val viewModel: MyViewModel by assistedViewModel { provider.get() }
    Since I know I'm only going to be using this ViewModel in a fragment, it would be nice to be able to get items from a fragment.
    a
    • 2
    • 4
  • j

    jw

    12/11/2021, 12:29 PM
    They're trivially expect/actual'd to work in MPP
    u
    • 2
    • 2
  • m

    Miguel

    12/22/2021, 10:10 AM
    Hello everyone, I got an issue with injecting something into a data class:
    data class Example @Inject constructor(
        val x: X,
        val string: String? = x.method()
    )
    In my dagger class I have:
    @Provides
    @Singleton
    fun x() = X()
    but whenever I want to instantiate an
    Example
    object. it asks me for
    x
    dependency which should always be injected. Is there any approach of how I can deal with this?
    d
    • 2
    • 1
  • j

    jean

    01/04/2022, 2:40 PM
    Let’s say I have a view showing a list of contacts and a second view showing the detail of a contact. I have used
    @ViewModelScoped
    for the second view ViewModel which works fine when I navigate the first time to a contact detail view, but on every following navigation, the view shows the details of the previous contact before loading and showing the new details. Should I implement a “reset” mechanism that clears the content of the view model when navigating to a new contact, or should I use a different scope? I considered to not use any scope but then screen orientation changes would make the view model trigger the load again. What do you advice me to do ?
    • 1
    • 1
  • y

    yassir kazzoune

    01/06/2022, 10:32 AM
    Can someone explain to me this part from Hilt Documentation (https://developer.android.com/training/dependency-injection/hilt-android#component-default): "Each Hilt component comes with a set of default bindings that Hilt can inject as dependencies into your own custom bindings. Note that these bindings correspond to the general activity and fragment types and not to any specific subclass. This is because Hilt uses a single activity component definition to inject all activities. Each activity has a different instance of this component."
    a
    • 2
    • 1
  • j

    jean

    01/13/2022, 1:06 PM
    does
    hiltViewModel()
    supports
    @Assisted
    constructor attributes now? Or does one still need to use a factory with
    @AssistedFactory
    ?
    f
    c
    r
    • 4
    • 11
  • w

    wellingtoncosta

    01/14/2022, 12:29 PM
    Hi. Is there possible to inject two different components into a same Activity?
    f
    • 2
    • 4
  • d

    dave08

    01/18/2022, 4:10 PM
    Why doesn't Hilt provide a
    @WorkComponent
    for WorkManager workers? Is there a way to make my own? Or is it intended, and there's something different to do for workers?
    c
    f
    t
    • 4
    • 4
Powered by Linen
Title
d

dave08

01/18/2022, 4:10 PM
Why doesn't Hilt provide a
@WorkComponent
for WorkManager workers? Is there a way to make my own? Or is it intended, and there's something different to do for workers?
c

Colton Idle

01/18/2022, 5:20 PM
I don't use workmanager, but no one from the workmanager/hilt team is here, so I doubt you will get an answer to your question. I'd file a bug/feature request. Also, there seems to be some sort of integration available in the docs: https://developer.android.com/training/dependency-injection/hilt-jetpack#workmanager
f

FunkyMuse

01/18/2022, 5:55 PM
Basically WorkManager has assisted injected constructor, you can put there dependencies that live in your custom scope
➕ 1
t

trevjones

01/19/2022, 3:16 AM
WorkerFactoryModule
is install to Singleton and the `androidx.work.Configuration`` is used to initialize inside of a double check lock to ensure a single instance of the factory is created. Which should mean that the only safe scope to depend on is
Singleton
or unscoped. Scoping the worker itself seems bad given each invocation is going to get its own instance of
WorkerParameters
d

dave08

01/19/2022, 4:07 AM
Yeah, but all worker dependencies are going to live throughout application life... So if multiple dependencies depend on one other, it's either create ot twice, or make it live during the application's lifetime...
View count: 19