I have just learnt manual dependency injection, but I am trying out Hilt to handle these dependency injections.
I want to inject a ViewModel
into a Fragment
. The fragment is contained within an Activity
. Right now, I have added the annotations to Application
, Activity
, and Fragment
.
@HiltAndroidApp
class MovieCatalogueApplication : Application()
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
...
}
@AndroidEntryPoint
class HomeFragment : Fragment() {
private lateinit var binding: FragHomeBinding
private val viewmodel: HomeViewModel by viewModels()
...
As can be seen, my HomeFragment
depends on HomeViewModel
. I have added a ViewModel injection as described here like so.
class HomeViewModel @ViewModelInject constructor(
private val movieRepository: MovieRepository,
private val showRepository: ShowRepository,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
However, the ViewModel
requires two repositories. Right now, my MovieRepository
is like so.
class MovieRepository (private val movieApi: MovieService) {
...
}
In the above code, MovieService
will be created by Retrofit using the Retrofit.create(class)
method. The interface used to create MovieService
is like so.
interface MovieService {
...
}
To get my Retrofit instance, I am using the following code.
object RetrofitService {
...
private var _retrofit: Retrofit? = null
val retrofit: Retrofit
get() {
return when (_retrofit) {
null -> {
_retrofit = Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
_retrofit!!
}
else -> _retrofit!!
}
}
}
I am not too sure how I can inject the Retrofit into the Repository to be used by my ViewModel
later on. Could someone give me some pointers or step-by-step instructions on how to do this?