Skip to content

Instantly share code, notes, and snippets.

@gustavkarlsson
Last active January 22, 2018 16:07
Show Gist options
  • Save gustavkarlsson/0f9ab8491ebdfdf9eaf5ada1cd1dface to your computer and use it in GitHub Desktop.
Save gustavkarlsson/0f9ab8491ebdfdf9eaf5ada1cd1dface to your computer and use it in GitHub Desktop.
Android ViewModel binding
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
/* ... */
bindData(MyViewModel())
}
private fun bindData(viewModel: MyViewModel) {
// From views
firstName.textChanges()
.subscribe(viewModel.setFirstName)
lastName.textChanges()
.subscribe(viewModel.setLastName)
// To views
viewModel.fullName
.subscribe(fullName.text())
}
}
class MyViewModel {
private val firstName = BehaviorRelay.create<CharSequence>()
val setFirstName: Consumer<CharSequence> = firstName
private val lastName = BehaviorRelay.create<CharSequence>()
val setLastName: Consumer<CharSequence> = firstName
val fullName: Observable<CharSequence> = Observable.combineLatest(firstName, lastName,
BiFunction<CharSequence, CharSequence, CharSequence> { first, last -> "$first $last" })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment