Skip to content

Instantly share code, notes, and snippets.

@mochadwi
Last active July 14, 2019 12:46
Show Gist options
  • Save mochadwi/1f7a3eef7a0b6806e6b68615c0923f71 to your computer and use it in GitHub Desktop.
Save mochadwi/1f7a3eef7a0b6806e6b68615c0923f71 to your computer and use it in GitHub Desktop.
ObservableField vs. LiveData
class Adapter(list: ArrayList<String>) : RecyclerView.ViewHolder(binding.root) {
// 02. using observablefield
// variable binding is your item.xml, generated into -> ItemBinding
lateinit val binding: ItemBinding // this should be defined on your project.
fun changeVariableA(msg: String) {
binding.apply {
message = msg
executePendingBindings() // directly tells the binding to be updated, without delay
}
}
}
// fragment.kt
class Fragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
// trigger this on your cases 01. livedata
viewModel.obsField.observe { msg ->
// listen changes and update the adapter variable
adapter.changeVariableA(msg)
}
viewModel.changeObs("abc")
// or trigger/call/invokes this on your cases directly 02. observablefield
adapter.changeVariableA(msg)
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="message"
type="String"/>
</data>
<TextView
android:id="@+id/tvMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{message}"/>
</layout>
// viewmodel.kt
class VM : ViewModel() {
// 01. LiveData
// private backing field, encapsulate the setter from outside class
private val _obsField = LiveEvent<String>()
val obsField: LiveData<String>
get() = _obsField
fun changeObs(msg: String) {
_obsField.value = msg
newObsField.set(msg)
}
// 02. using observablefield
val newObsField = ObservableField<String>("test")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment