Dagger2 + ViewModel + Repository
I am new to Dagger 2 and trying to implement it in Kotlin. Here i am trying to inject my repository object into viewmodel. I am successfully able to inject it this way
public class LoginViewModel @Inject constructor(var mApplication: Application, var repository: LoginRepository) :
ViewModel() {
This is how my repository looks like
class LoginRepository @Inject constructor(val retrofit: APICallInterface) {
This is how my module looks like
@Module
class BaseModule {
@Provides
fun getRetrofit(): APICallInterface {
return Retrofit.Builder()
.baseUrl("https://samples.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build().create(APICallInterface::class.java)
}
What i am unable to understand is how Dagger 2 is able to provide an object for repository as i have not mentioned it in any module with @Provides annotation.
I have tried following many blogs and few stckoverflow questions available here but none of them is solving my doubt.
Any help/explanation will be appreciated.
Answer
What i am unable to understand is how Dagger 2 is able to provide an object for repository as i have not mentioned it in any module with @Provides annotation.
You're using constructor injection by annotating the constructor with @Inject
:
[
@Inject
] Identifies injectable constructors, methods, and fields.
So, by adding the annotation, Dagger becomes aware of the constructor and knows how to create the object when needed.
class LoginRepository @Inject constructor(..)
If your constructor wouldn't have the annotation on it then you'd need a @Provides
annotated method in a module so that Dagger can access the dependency, but you should use @Provides
annotated methods primarily for objects that need additional setup and/or initialization.
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View