Skip to content

Instantly share code, notes, and snippets.

View JoseAlcerreca's full-sized avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
myViewModel.navigateToDetails.observe(this, Observer {
it.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled
startActivity(DetailsActivity...)
}
})
class MainViewModel {
val repositoryResult = Transformations.switchMap(userManager.user) { user ->
repository.getDataForUser(user)
}
}
val liveData1: LiveData<Int> = ...
val liveData2: LiveData<Int> = ...
val result = MediatorLiveData<Int>()
result.addSource(liveData1) { value ->
result.setValue(value)
}
result.addSource(liveData2) { value ->
result.setValue(value)
fun blogpostBoilerplateExample(newUser: String): LiveData<UserDataResult> {
val liveData1 = userOnlineDataSource.getOnlineTime(newUser)
val liveData2 = userCheckinsDataSource.getCheckins(newUser)
val result = MediatorLiveData<UserDataResult>()
result.addSource(liveData1) { value ->
result.value = combineLatestData(liveData1, liveData2)
}
private fun combineLatestData(
onlineTimeResult: LiveData<Long>,
checkinsResult: LiveData<CheckinsResult>
): UserDataResult {
val onlineTime = onlineTimeResult.value
val checkins = checkinsResult.value
// Don't send a success until we have both results
if (onlineTime == null || checkins == null) {
class SharedLiveDataSource(val dataSource: MyDataSource) {
// Caution: this LiveData is shared across consumers
private val result = MutableLiveData<Long>()
fun loadDataForUser(userId: String): LiveData<Long> {
result.value = dataSource.getOnlineTime(userId)
return result
}
}
sharedLiveDataSource.loadDataForUser("1").observe(this, Observer {
// Show result on screen
})
class SlowRandomNumberGenerator {
private val rnd = Random()
fun getNumber(): LiveData<Int> {
val result = MutableLiveData<Int>()
// Send a random number after a while
Executors.newSingleThreadExecutor().execute {
Thread.sleep(500)
result.postValue(rnd.nextInt(1000))
var lateinit randomNumber: LiveData<Int>
/**
* Called on button click.
*/
fun onGetNumber() {
randomNumber = Transformations.map(numberGenerator.getNumber()) {
it
}
}
viewmodel.randomNumber.observe(this, Observer { number ->
numberTv.text = resources.getString(R.string.random_text, number)
})