Injecting Interface to an App Activity – Hilt+Android

Issue

New to DI. Let’s say there is an interface XYZ in a module ABC, which is being used by the main app project as a dependency. I want to inject that interface XYZ to the MainActivity in the main project. Please see below how I am trying.

ABC Module Contents

XYZ

    interface XYZ {
       fun init()
    }

TestView class implementing interface

class TestView: XYZ {  
    override fun init(){
    }
}

Main project contents

AppModule class

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Provides
    fun xyz(): XYZ = TestView()
    
}

MainActivity

@AndroidEntryPoint
class MainActivity : AppCompactActivity() {
   @Inject lateinit var xyz : XYZ

   override onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       xyz.init()
   }
}
  1. Please let me know if there is something wrong with this.
  2. If I use the same interface for another class let’s say TestView2 and use it in another activity in main project. Can I provide that view as well in the AppModule class? If yes How will I differentiate it from the first one as Both will be using the same interface?

Thanks in advance.

Solution

I’m not a senior dev, so take my words with a grain of salt 😉

Please let me know if there is something wrong with this.

Yes and no (see below)

It will work and some people prefer to provide an interface this way,

however it is better to use @Binds (it generates less code, which makes your app smaller and the build times are quicker)

you can find how to use it here

If I use the same interface for another class let’s say TestView2 and use it in another activity in main project. Can I provide that view as well in the AppModule class? If yes How will I differentiate it from the first one as Both will be using the same interface?

If you create 2 provide methods which return the same type, dagger won’t know which method to use to provide your dependency, that’s why you can name your providers (using the @Named annotation), you can find more about it here

(also, just a comment: Using multiple activities in one application isn’t really recommended anymore, and I’m personally against it)

Answered By – JustSightseeing

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published