Skip to content

Instantly share code, notes, and snippets.

@alwarren
Last active February 28, 2018 06:49
Show Gist options
  • Save alwarren/46576a293d76678fb8b43cc75dff04a0 to your computer and use it in GitHub Desktop.
Save alwarren/46576a293d76678fb8b43cc75dff04a0 to your computer and use it in GitHub Desktop.
Android LiveData ViewModel (Kotlin/Dagger)
internal class HelloViewModel @Inject constructor(private val dataSource: Hello) : ViewModel() {
// observed by ViewModel as a trigger to retrieve data from the source
private var liveEndpoint: MutableLiveData<String> = MutableLiveData()
// observed by Activity/Fragment or some other class as a trigger to do something with the data
private var liveData: LiveData<String>
init {
// default observable endpoint
liveEndpoint.value = dataSource.text
// observe endpoint and reload observable liveData when endpoint changes
liveData = Transformations.switchMap(liveEndpoint) {
dataSource.fetchData(liveEndpoint.value!!)
}
}
// trigger the observable endpoint to retrieve data
fun setData(value: String) {
liveEndpoint.value = value
}
// retrieve the observable data
fun getData(): LiveData<String> = liveData
}
data class Hello(var text: String = "Hello World!!!") {
private val liveData = MutableLiveData<String>()
fun fetchData(value: String): LiveData<String> {
liveData.value = value
return liveData
}
}
class HelloViewModelActivity : DaggerAppCompatActivity() {
@Inject lateinit var hello: Hello
@Inject lateinit var factory: ViewModelProvider.Factory
private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProviders.of(this, factory).get(HelloViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hello)
initializeViews()
viewModel.getData().observe(this, Observer {
it?.let { data -> updateUI(data) }
})
}
private fun updateUI(data: String) {
textHello.text = data
}
private fun initializeViews() {
textHello.text = hello.text
buttonHello.setOnClickListener {
val text = editHello.text.toString()
if (!text.isEmpty())
viewModel.setData(text)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment