https://kotlinlang.org logo
#random
Title
# random
c

Colton Idle

01/04/2023, 7:35 AM
Tips on how to improve this? I guess I shouldn't inject an apiService into my ViewModel? I should inject a repository instead?
Copy code
@HiltViewModel
class MyViewModel @Inject constructor(private val api: MyApi) : ViewModel() {
  val state = HomeScreenState()
  init {
    state.fetchingData = true
    viewModelScope.launch {
      when (val response = apiService.getItems()) {
        is ApiResult.Success -> {
          state.items.addAll(response.value)
        }
      }
      state.fetchingData = false
    }
  }
g

gildor

01/04/2023, 8:59 AM
state
is mutable, how would client code would know that it updated? I would probably do something like: val state: Flow<HomeScreenState> = flow { emit(HomeScreenState.Loading) when (val response = apiService.getItems()) { is ApiResult.Success -> emit(HomeScreenState.Success(response.value)) is Error -> emit(HomeScreenState.Error(…)) } // Add optional sharing, if you want to preserver result between subscriptions .shareIn(…)