Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android databinding and LiveData: Can't bind to value in LiveData property

I'm trying out databinding for a view that's supposed to display data exposed through a LiveData property in a viewmodel, but I've found no way to bind the object inside the LiveData to the view. From the XML I only have access to the value property of the LiveData instance, but not the object inside it. Am I missing something or isn't that possible?

My ViewModel:

class TaskViewModel @Inject
internal constructor(private val taskInteractor: taskInteractor)
    : ViewModel(), TaskContract.ViewModel {

    override val selected = MutableLiveData<Task>()
    val task: LiveData<Task> = Transformations.switchMap(
        selected
    ) { item ->
        taskInteractor
            .getTaskLiveData(item.task.UID)
    }
    ... left out for breivety ... 
}

I'm trying to bind the values of the task object inside my view, but when trying to set the values of my task inside my view I can only do android:text="@={viewmodel.task.value}". I have no access to the fields of my task object. What's the trick to extract the values of your object inside a LiveData object?

My task class:

@Entity(tableName = "tasks")
data class Task(val id: String, 
                val title: String, 
                val description: String?, 
                created: Date, 
                updated: Date, 
                assigned: String?)
like image 951
Bohsen Avatar asked Nov 29 '22 21:11

Bohsen


1 Answers

For LiveData to work with Android Data Binding, you have to set the LifecycleOwner for the binding

binding.setLifecycleOwner(this)

and use the LiveData as if it was an ObservableField

android:text="@{viewmodel.task}"

For this to work, Task needs to implement CharSequence. Using viewmodel.task.toString() might work as well. To implement a two-way-binding, you'd have to use MutableLiveData instead.

like image 163
tynn Avatar answered Dec 04 '22 13:12

tynn