I am exposing Ui state to a view(like Activity) from ViewModel by using stateIn()
now.
this below is my ViewModel code .
MainViewModel.kt
@HiltViewModel
class MainViewModel @Inject constructor (
private val listUseCase: GetUserListUseCase
): ViewModel() {
private var _listUiState = listUseCase.invoke().stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = UiState.Loading
)
val listUiState: StateFlow<UiState<List>> = _listUiState
}
And I want to add a function which fetches a new list from an api.
So, I made fetchNewList()
.
class MainViewModel @Inject constructor (
private val listUseCase: GetUserListUseCase
): ViewModel() {
private var _listUiState = listUseCase.invoke().stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = UiState.Loading
)
val listUiState: StateFlow<UiState<List>> = _listUiState
fun fetchNewList() = viewModelScope.launch {
_listUiState = listUseCase.invoke().stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = UiState.Loading
)
}
}
But the code above is not working. Nothing happens…
I feel like the reason why it wasn’t updated is that i didn’t access to _listUiState
with .value
.
And i also want to use stateIn() in fetchNewList()
because SharingStarted
is very useful and efficient.
SharingStarted
gives me the following benefits which are what i care about now.
â—Ź When the user sends your app to the background, updates coming from other layers will stop after five seconds, saving battery.
â—Ź The latest value will still be cached so that when the user comes back to it, the view will have some data immediately.
â—Ź Subscriptions are restarted and new values will come in, refreshing the screen when available.
So, How can i update the StateFlow with new list by using stateIn(SharingStarted.WhileSubscribed(5000))??
is it possible or if not, i hope i get good alternatives that achieve the same effect of WhileSubscribed()
.