Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helpful Android-Kotlin LiveData utilities
//--------------------------------
// CHECK THE COMMENTS FOR UPDATES!
//--------------------------------
/*
* Copyright (C) 2017 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.Transformations
/**
* This function creates a [LiveData] of a [Pair] of the two types provided. The resulting LiveData is updated whenever either input LiveData updates and both LiveData have updated at least once before.
*
* If the zip of A and B is C, and A and B are updated in this pattern: `AABA`, C would be updated twice (once with the second A value and first B value, and once with the third A value and first B value).
*
* @param a the first LiveData
* @param b the second LiveData
* @author Mitchell Skaggs
*/
fun <A, B> zipLiveData(a: LiveData<A>, b: LiveData<B>): LiveData<Pair<A, B>> {
return MediatorLiveData<Pair<A, B>>().apply {
var lastA: A? = null
var lastB: B? = null
fun update() {
val localLastA = lastA
val localLastB = lastB
if (localLastA != null && localLastB != null)
this.value = Pair(localLastA, localLastB)
}
addSource(a) {
lastA = it
update()
}
addSource(b) {
lastB = it
update()
}
}
}
/**
* This is merely an extension function for [zipLiveData].
*
* @see zipLiveData
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.zip(b: LiveData<B>): LiveData<Pair<A, B>> = zipLiveData(this, b)
/**
* This is an extension function that calls to [Transformations.map].
*
* @see Transformations.map
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.map(function: (A) -> B): LiveData<B> = Transformations.map(this, function)
/**
* This is an extension function that calls to [Transformations.switchMap].
*
* @see Transformations.switchMap
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.switchMap(function: (A) -> LiveData<B>): LiveData<B> = Transformations.switchMap(this, function)
@bandrews568

This comment has been minimized.

Copy link

@bandrews568 bandrews568 commented Mar 24, 2018

This is super helpful! 👍

Could also use an infix call for the zip:

infix fun <A, B> LiveData<A>.zip(that: LiveData<B>): LiveData<Pair<A, B>> = zipLiveData(this, that)
@magneticflux-

This comment has been minimized.

Copy link
Owner Author

@magneticflux- magneticflux- commented Jun 7, 2018

Check here for an updated library version of this code! I incorporated various suggestions and packaged it as an Android Library for proper transitive dependency resolution, the potential to add more features, and unit tests for the more complete features. Best of all, it's licensed under the LGPL v3 so you can now legally use it in your closed-source applications!

To use:

repositories {
   jcenter()
}

dependencies {
   implementation 'com.github.magneticflux:kotlin-livedata-utils:0.3.3'
}
@Fantasycheese

This comment has been minimized.

Copy link

@Fantasycheese Fantasycheese commented Jun 25, 2018

I believe this kind of behavior is called "Combine Latest" in RX terminology. I know Livedata is not a RX replication, but "Combine Latest" is a more specific name anyway. If you want to do "Zip" like in RX, simply set null to both lastA/lastB after emitting new value should do the trick.

@wahibhaq

This comment has been minimized.

Copy link

@wahibhaq wahibhaq commented Jul 8, 2018

I actually came back to say the same thing which @Fantasycheese has already mentioned. This implementation is actually referred as CombineLatest operator so I hope other devs don't confuse with Zip operator.

@latas

This comment has been minimized.

Copy link

@latas latas commented Jul 25, 2018

The proper zip should be like this (doesn't look so nice tho):

fun <A, B> zipLiveData(a: LiveData<A>, b: LiveData<B>): LiveData<Pair<A, B>> {

    return MediatorLiveData<Pair<A, B>>().apply {
        var lastA: A? = null
        var lastB: B? = null
        var aIsTheLastUpdated = false
        var bIsTheLastUpdated = false

        fun update(b: B?) {
            if (b != null && lastA != null && aIsTheLastUpdated) {
                this.value = Pair(lastA!!, b)
            }
            bIsTheLastUpdated = true
            aIsTheLastUpdated = false
            lastB = b
        }

        fun update(a: A?) {
            if (a != null && lastB != null && bIsTheLastUpdated) {
                this.value = Pair(a, lastB!!)
            }
            aIsTheLastUpdated = true
            bIsTheLastUpdated = false
            lastA = a
        }

        addSource(a) {
            update(it)
        }
        addSource(b) {
            update(it)
        }
    }
}
@friederbluemle

This comment has been minimized.

Copy link

@friederbluemle friederbluemle commented Oct 3, 2018

Could someone explain this part:

            val localLastA = lastA
            val localLastB = lastB
            if (localLastA != null && localLastB != null)
                this.value = Pair(localLastA, localLastB)

What's the purpose of creating the local variables?

@magneticflux-

This comment has been minimized.

Copy link
Owner Author

@magneticflux- magneticflux- commented Apr 17, 2019

@friederbluemle lastA and lastB are mutable and nullable, so their contents can change at any time due to multithreaded code. localLastA and localLastB are immutable and nullable, so their contents are fixed and can be asserted in sequence (localLastA != null && localLastB != null) without possibility of localLastA changing after evaluation. It's all so that there's no possibility of a null slipping through, even in concurrent code.

@tlozovyi

This comment has been minimized.

Copy link

@tlozovyi tlozovyi commented Apr 1, 2020

That's single time zip which will behave as combineWith once both value is not null. Here's updated version. I've also added dynamic result block.

fun <A, B, R> zipLiveData(
        a: LiveData<A>,
        b: LiveData<B>,
        block: (A, B) -> R
): LiveData<R> {
    return MediatorLiveData<R>().apply {
        var lastA: A? = null
        var lastB: B? = null

        fun update() {
            val localLastA = lastA
            val localLastB = lastB
            if (localLastA != null && localLastB != null) {
                this.value = block.invoke(localLastA, localLastB)
                lastA = null
                lastB = null
            }
        }

        addSource(a) {
            lastA = it
            update()
        }
        addSource(b) {
            lastB = it
            update()
        }
    }
}

fun <A, B, R> LiveData<A>.zipWith(b: LiveData<B>, block: (A, B) -> R): LiveData<R> = zipLiveData(this, b, block)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment