I have `sealed` class `AppState` with 4 states (3...
# android
d
I have
sealed
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 thread
// 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) { 
					
				}
			}
		}
	}
}
image.png
z
when (val a = appState)
d
Thanks @Zun Although this works we get a lint warning as follows
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