Sudhir Singh Khanger
11/01/2018, 9:53 AMclass DetailViewModelFactory(private val id: Int) : ViewModelProvider.Factory {
private val movieRepository: MovieRepository = Injector.getAppComponent().getMovieRepository()
I was wondering if this piece of code could be rewritten in primary and secondary constructor form where MovieRepository
injected via Dagger 2. (Code:- https://github.com/sudhirkhanger/Genius)gildor
11/01/2018, 9:55 AMSudhir Singh Khanger
11/01/2018, 11:48 AMgildor
11/01/2018, 12:13 PMgildor
11/01/2018, 12:14 PMSudhir Singh Khanger
11/02/2018, 3:57 AMMovieRepository
via Dagger 2 and provide id: Int
when the class is initialized.
If I declare MovieRepository
in the primary constructor then I don't have any access to it in the secondary constructor to pass on to the primary. If I declare id in the primary constructor then my secondary constructor will contain both MovieRepository
and id: Int
but then I don't want to provide MovieRepository
from where I will initialize DetailViewModelFactory
class. So I guess above should be fine.
Unless there is a way where I can inject only one parameter via Dagger 2 out of several and when I initialize the class I only have to provide the id.gildor
11/02/2018, 5:00 AMgildor
11/02/2018, 5:00 AMcreate(id)
Sudhir Singh Khanger
11/04/2018, 5:57 PMgildor
11/05/2018, 1:05 PMgildor
11/05/2018, 1:07 PMDavid
11/14/2018, 10:14 AMgildor
11/14/2018, 10:16 AMDavid
11/14/2018, 10:36 AMclass @AssistedInject DetailViewModelFactory(
@Assisted private val id: Int, // Your runtime state
private val repo: MovieRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DetailViewModel::class.java))
@Suppress("UNCHECKED_CAST")
return DetailViewModel(repo, id) as T
throw IllegalArgumentException("Unknown ViewModel class")
}
// Instructions to Dagger for code-gen
@AssistedInject.Factory
interface Factory {
fun create(id: Int): DetailViewModelFactory
}
}
Just hand wrote this. Not sure if it’s 100%. I use the subcomponent route at present rather than AssistedInject for injecting runtime state