Home > database >  In Android Compose function, what's the best way to convert a nullable LiveData variable to Com
In Android Compose function, what's the best way to convert a nullable LiveData variable to Com

Time:03-16

For a normal LiveData variable in the view model, eg

val data = MutableLiveData<City>()

We can observe it using

data.observeAsState()

My question is, say I have an optional LiveData variable like

var data: MutableLiveData<City>? = null

What would be the proper way to handle it in a composable function?

At the time, the best way I can see is to unwrap everything outside the composable function

group?.let {
  it.observe(this) { groupData ->
      Content(groupData)
  }
}?: run {
  Content(null)       
}


@Compasable
fun Content(group: Group?) {
  ...
}

Is there a more Compose-oriented way to do this?

CodePudding user response:

You can observe it from Composable function pretty much the same way you do it with NonNull LiveData, just using some kotlin null-safe operators:

val group: Group? = data?.observeAsState()?.value

I guess that most of your confusion comes from using the by property delegate, which doesn't really work (does more harm than good) for Nullable LiveData. Firstly, you will have to do something like the following example, which is not very nice, and then you won't be able to use Kotlin's smart cast because "group is a property that has open or custom getter". However, using .value is equivalent to by delegation and in some cases better.

// this is nice
val group: Group by data.observeAsState()
// you can also do this, but don't
val group: Group? by (data?.observeAsState() ?: mutableStateOf(null))
  • Related