Does any one know the proper way to access the Liv...
# compose
j
Does any one know the proper way to access the LiveData that you get from a room database in compose? I'm sure the DB is not empty, because when I do the following the correct entry is printed:
Copy code
val items = viewModel.readAllData.observeAsState()
val TAG = "check"
val item1 = items.value?.get(0)?.original
Log.i(TAG,item1.toString())
However, if I try to show the text in a Text element like so
Copy code
Column{
    Text(text = item1!!)
}
it tells me the List is empty ¯\_(ツ)_/¯
c
!!
you have an unsafe operator here. You should check if it is not null (and empty), and display it in that case.
Copy code
val items by viewModel.readAllData.observeAsState()

if (!items.isNullOrEmpty()) {
  Text(text = items!!.first()) // safe to call here
}
j
@Csaba Kozák Thank you. I did think of doing that, but I thought it was bad practice in Kotlin to check for nullity manually? Also, why does it work in the Log? (if it's a long explanation please don't bother).
c
In the first snippet, you are using a safe-call operator
?.
, so event when it is null first, you should see itt logging
null
, but no crash.
Well, you can call it manual null check, but in the end, it generates the same code. Instead of the
if
, you could also use
items?.let {
if you want.
🙇‍♂️ 1