Danish Ansari
01/28/2022, 6:50 AMsealed
class AppState
with 4 states (3 object and 1 one data class having 1 immutable property). It is used in ViewModel
as private MutableLiveData
and exposed to activity as LiveData
I'm using it in compose using LiveData.observeAsState()
Now the issue I'm facing is that when I use the variable State<AppState>
(variable name is appState) using when
block I'm able to access that 1 data classess property but I'm getting compilation error (Smart cast to 'AppState.Success' is impossible, because 'appState' is a property that has open or custom getter)
Code snippet inside threadDanish Ansari
01/28/2022, 6:50 AMkotlin
private val _appState = MutableLiveData<AppState>(AppState.Loading)
val appState: LiveData<AppState> = _appState
// Sealed class
kotlin
sealed class AppState {
object Loading : AppState()
data class Success(val userList: List<User>) : AppState()
object NoInternet : AppState()
object UnExpectedError : AppState()
}
// UI Code
Surface {
val appState by mainViewModel.appState.observeAsState()
when (appState) {
is AppState.Loading -> // ...
is AppState.NoInternet -> // ...
is AppState.UnExpectedError -> // ...
is AppState.Success -> {
LazyColumn {
// Getting error in below line
items(appState.userList) {
}
}
}
}
}
Danish Ansari
01/28/2022, 6:52 AMZun
01/28/2022, 7:08 AMDanish Ansari
01/28/2022, 7:14 AMDanish Ansari
01/28/2022, 7:15 AMby
delegate I used value
property of State
class
I changed
val appState by mainViewModel.appState.observeAsState()
to
val appState = mainViewModel.appState.observeAsState().value