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 thread
Danish Ansari
01/28/2022, 6:50 AM
// ViewModel
Copy code
kotlin
private val _appState = MutableLiveData<AppState>(AppState.Loading)
val appState: LiveData<AppState> = _appState
// Sealed class
Copy code
kotlin
sealed class AppState {
object Loading : AppState()
data class Success(val userList: List<User>) : AppState()
object NoInternet : AppState()
object UnExpectedError : AppState()
}
// UI Code
Copy 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 AM
image.png
z
Zun
01/28/2022, 7:08 AM
when (val a = appState)
d
Danish Ansari
01/28/2022, 7:14 AM
Thanks @Zun Although this works we get a lint warning as follows
Danish Ansari
01/28/2022, 7:15 AM
What worked for me was to instead of using
by
delegate I used
value
property of
State
class
I changed
Copy code
val appState by mainViewModel.appState.observeAsState()
to
Copy code
val appState = mainViewModel.appState.observeAsState().value