0

I'm trying to control ViewModel from a fragment by sending category_id and pass it to the repository which is injected by Hilt. But ViewModel cant see repository outside of init block. What did I miss?

@HiltViewModel
class ProjectViewModel @Inject constructor(
repository: ScienceTrackerRepository
) : ViewModel() {

private val _flow = MutableStateFlow(LoadUiState.Success(emptyList()))
val flow: StateFlow<LoadUiState> = _flow.asStateFlow()

fun loadProjects(categoryId: Int) {
    viewModelScope.launch {
        repository.getProjects(categoryId) // unresolved reference "repository"
        repository.flowProjects.collect { feed ->
            _flow.value = LoadUiState.Success(feed)
        }
    }
}

init {
    viewModelScope.launch {
        repository.getProjects(0) 
        repository.flowProjects.collect { feed ->
            _flow.value = LoadUiState.Success(feed)
        }
    }
}
}
Dmitry
  • 130
  • 6

1 Answers1

0

you need to add var or val keyword like this:

@HiltViewModel class ProjectViewModel @Inject constructor( val repository: ScienceTrackerRepository ) : ViewModel() {

}

to access the constructor params outside the init block.

  • @Dmitry see https://stackoverflow.com/a/52567485/4704327 for more details – Anand May 31 '21 at 21:01
  • var or val both are use for creating the variable. when we add these keywords in constructor then kotlin treat constructor parameter as a local variable. if you want to create a local variable in kotlin then you have to write val or var with it else kotlin give you error. – Muhammad Danish May 31 '21 at 21:27