Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 35d92c7c authored by Josh Tsuji's avatar Josh Tsuji
Browse files

Add overloads to Flow.sample to allow sampling multiple flows.

We have an increasing number of flows that sample a combination of
several other flows, which results in extra tuple transform boilerplate:

a.sample(combine(b, c, d, ::Triple), ::toQuad).collect {
    (a, b, c, d) -> ...

Adding another flow also requires updating both transforms. This
cleans that up:

a.sample(b, c, d).collect {
    (a, b, c, d) -> ...

Bug: 278086361
Test: N/A
Flag: N/A
Change-Id: Ic71ea6a23a4138fb8989e9564b0f93d7ae916c74
parent 4624eedc
Loading
Loading
Loading
Loading
+42 −0
Original line number Diff line number Diff line
@@ -16,6 +16,9 @@

package com.android.systemui.util.kotlin

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine

class Utils {
    companion object {
        fun <A, B, C> toTriple(a: A, bc: Pair<B, C>) = Triple(a, bc.first, bc.second)
@@ -27,6 +30,45 @@ class Utils {

        fun <A, B, C, D, E> toQuint(a: A, bcde: Quad<B, C, D, E>) =
            Quint(a, bcde.first, bcde.second, bcde.third, bcde.fourth)

        /**
         * Samples the provided flows, emitting a tuple of the original flow's value as well as each
         * of the combined flows' values.
         *
         * Flow<A>.sample(Flow<B>, Flow<C>) -> (A, B, C)
         */
        fun <A, B, C> Flow<A>.sample(b: Flow<B>, c: Flow<C>): Flow<Triple<A, B, C>> {
            return this.sample(combine(b, c, ::Pair), ::toTriple)
        }

        /**
         * Samples the provided flows, emitting a tuple of the original flow's value as well as each
         * of the combined flows' values.
         *
         * Flow<A>.sample(Flow<B>, Flow<C>, Flow<D>) -> (A, B, C, D)
         */
        fun <A, B, C, D> Flow<A>.sample(
            b: Flow<B>,
            c: Flow<C>,
            d: Flow<D>
        ): Flow<Quad<A, B, C, D>> {
            return this.sample(combine(b, c, d, ::Triple), ::toQuad)
        }

        /**
         * Samples the provided flows, emitting a tuple of the original flow's value as well as each
         * of the combined flows' values.
         *
         * Flow<A>.sample(Flow<B>, Flow<C>, Flow<D>, Flow<E>) -> (A, B, C, D, E)
         */
        fun <A, B, C, D, E> Flow<A>.sample(
            b: Flow<B>,
            c: Flow<C>,
            d: Flow<D>,
            e: Flow<E>,
        ): Flow<Quint<A, B, C, D, E>> {
            return this.sample(combine(b, c, d, e, ::Quad), ::toQuint)
        }
    }
}