Last active
January 22, 2018 16:07
-
-
Save gustavkarlsson/0f9ab8491ebdfdf9eaf5ada1cd1dface to your computer and use it in GitHub Desktop.
Android ViewModel binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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