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

Commit 954c40f0 authored by Caitlin Shkuratov's avatar Caitlin Shkuratov
Browse files

[CS] Define an #alwaysCollectFlow method that can be used from Java.

As we move more CentralSurfacesImpl methods to flows, Java classes will
need to listen to them. Some of these Java classes need to be *always*
listening to flows and cannot tie the flow collection to a specific
view. This CL adds a helper method for Java classes to do that.
ag/23710783 will use this helper method.

As we move more of our codebase to recommended architecture, I hope this
method will be used less frequently and can eventually be deleted.

Bug: 277764509
Test: compiles
Change-Id: Iff8eba81597626941b34b2fdc1b96d0acd9ca5e5
parent 78d1d951
Loading
Loading
Loading
Loading
+32 −0
Original line number Diff line number Diff line
@@ -19,12 +19,44 @@ package com.android.systemui.util.kotlin
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.lifecycle.repeatWhenAttached
import java.util.function.Consumer
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/** A class allowing Java classes to collect on Kotlin flows. */
@SysUISingleton
class JavaAdapter
@Inject
constructor(
    @Application private val scope: CoroutineScope,
) {
    /**
     * Collect information for the given [flow], calling [consumer] for each emitted event.
     *
     * Important: This will immediately start collection and *never* stop it. This should only be
     * used by classes that *need* to always be collecting a value and processing it. Whenever
     * possible, please use [collectFlow] instead; that method will stop the collection when a view
     * has disappeared, which will ensure that we don't perform unnecessary work.
     *
     * Do *not* call this method in a class's constructor. Instead, call it in
     * [com.android.systemui.CoreStartable.start] or similar method.
     */
    fun <T> alwaysCollectFlow(
        flow: Flow<T>,
        consumer: Consumer<T>,
    ): Job {
        return scope.launch { flow.collect { consumer.accept(it) } }
    }
}

/**
 * Collect information for the given [flow], calling [consumer] for each emitted event. Defaults to