I have ViewModel where I need in runtime inject some parameters but also in this ViewModel i need repository. Not sure is it possible with dagger hilt to combine Assisted Inject and Inject. If I try now to use communityFeedRepository it gives me error:
com.test.context.community.repository.CommunityFeedRepository is injected at com.test.context.community.CommunityFeedViewModel(…, communityFeedRepository) com.test.context.community.CommunityFeedViewModel.Factory is requested at com.test.context.di.ViewModelFactoryProvider.communityFeedViewModelFactory()
Here is my code:
class CommunityFeedViewModel
@AssistedInject
constructor(
@Assisted("preloadedTiles") private val preloadedTiles: List<Tile>,
@Assisted("path") private val path: String,
@Assisted("token") private val token: String?,
// private var communityFeedRepository: CommunityFeedRepository
) : ViewModel() {
var tiles: List<Tile> = preloadedTiles
private val vmPath = path
var vmToken: String? = token
private val tileState = MutableStateFlow(tiles)
val til = tileState.asStateFlow()
private suspend fun loadTiles() {
/*communityFeedRepository.getCommunityFeedTiles(vmPath, vmToken).onSuccess {
tileState.value = it.tiles
vmToken = it.token
}*/
}
init {
viewModelScope.launch {
if (tiles.isEmpty()) {
loadTiles()
}
}
}
@AssistedFactory
interface Factory {
fun create(
@Assisted("preloadedTiles") preloadedTiles: List<Tile>,
@Assisted("path") path: String,
@Assisted("token") token: String?
): CommunityFeedViewModel
}
@Suppress("UNCHECKED_CAST")
companion object {
fun provideFactory(
assistedFactory: Factory,
preloadedTiles: List<Tile>,
path: String,
token: String?
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return assistedFactory.create(preloadedTiles, path, token) as T
}
}
}
}
@Composable
fun communityFeedViewModel(
preloadedTiles: List<Tile>,
path: String,
token: String?
): CommunityFeedViewModel {
val factory = EntryPointAccessors.fromActivity(
LocalContext.current as Activity,
ViewModelFactoryProvider::class.java
).communityFeedViewModelFactory()
return viewModel(
factory = CommunityFeedViewModel.provideFactory(
factory,
preloadedTiles = preloadedTiles,
path = path,
token = token
), key = path
)
}