Skip to content

Instantly share code, notes, and snippets.

@magneticflux-
Last active February 3, 2023 19:08
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save magneticflux-/044c9d7a3cea431aa0e4f4f4950a2898 to your computer and use it in GitHub Desktop.
Save magneticflux-/044c9d7a3cea431aa0e4f4f4950a2898 to your computer and use it in GitHub Desktop.
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
Copy link

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-
Copy link
Author

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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-
Copy link
Author

@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
Copy link

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