I have a sealed class which is being sending via StateFlow. How to cast it in order to retrieve an enclosed value? I cannot find any example of syntax for databinding expressions.
dataclass UserInfo(val name: String)
sealed class ResultOf<out T> {
data class Success<out R>(val content: R): ResultOf<R>()
data class Failure(val throwable: Throwable): ResultOf<Nothing>()
}
val model = ResultOf.Success.content(UserInfo("John Doe"))
<variable
name = "viewModel"
type="com.example.hello.user.ResultOf"/>
<TextView
android:id="@+id/name"
android:text="@{ ??? }"
/>
viewModel.Success.content.name (UserInfo)viewModel.content.name (viewModel as UserInfo).content.name
None of the above works neither
Not sure if there is a way to go about this using casting in a conditional statement in XML at the moment.
You could go about this by creating a BindingAdapter. Like so:
data class User(val name: String)
sealed class ResultOf<out T: Any> {
data class Success<out R: Any>(val content: R): ResultOf<R>()
data class Failure(val throwable: Throwable): ResultOf<Nothing>()
}
The BindingAdapter:
@BindingAdapter("app:userName")
fun TextView.setUserName(result: ResultOf<User>) {
text = when(result) {
is ResultOf.Success -> result.content.name
is ResultOf.Failure -> ""
}
}
Layout file:
<data>
<import type="com.example.hello.user.ResultOf" />
<import type="com.example.hello.user.User" />
<variable
name="userResult"
type="ResultOf<User>" />
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:userName="@{userResult}"/>