Skip to content

Instantly share code, notes, and snippets.

View JoseAlcerreca's full-sized avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
/**
* Sets the value to the result of a function that is called when both `LiveData`s have data
* or when they receive updates after that.
*/
fun <T, A, B> LiveData<A>.combineAndCompute(other: LiveData<B>, onChange: (A, B) -> T): MediatorLiveData<T> {
var source1emitted = false
var source2emitted = false
val result = MediatorLiveData<T>()
/**
* Notifies the event LiveData of a new request for a random number.
*/
fun onGetNumber() {
newNumberEvent.value = Event(Unit)
}
private val newNumberEvent = MutableLiveData<Event<Any>>()
val randomNumber: LiveData<Int> = Transformations.switchMap(newNumberEvent) {
numberGenerator.getNumber()
}
viewmodel.randomNumber.observe(this, Observer { number ->
numberTv.text = resources.getString(R.string.random_text, number)
})
var lateinit randomNumber: LiveData<Int>
/**
* Called on button click.
*/
fun onGetNumber() {
randomNumber = Transformations.map(numberGenerator.getNumber()) {
it
}
}
val randomNumber = MediatorLiveData<Int>()
/**
* *Don't do this.*
*
* Called when the user clicks on a button
*
* This function adds a new source to the result but it doesn't remove the previous ones.
*/
fun onGetNumber() {
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))
class SharedLiveDataSource(val dataSource: MyDataSource) {
fun loadDataForUser(userId: String): LiveData<Long> {
val result = MutableLiveData<Long>()
result.value = dataSource.getOnlineTime(userId)
return result
}
}
sharedLiveDataSource.loadDataForUser("2").observe(this, Observer {
// Show result on screen
})
sharedLiveDataSource.loadDataForUser("1").observe(this, Observer {
// Show result on screen
})