1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.systemui.common.coroutine 18 19 import kotlin.experimental.ExperimentalTypeInference 20 import kotlinx.coroutines.ExperimentalCoroutinesApi 21 import kotlinx.coroutines.channels.Channel 22 import kotlinx.coroutines.channels.ProducerScope 23 import kotlinx.coroutines.flow.Flow 24 import kotlinx.coroutines.flow.buffer 25 import kotlinx.coroutines.flow.callbackFlow 26 27 object ConflatedCallbackFlow { 28 29 /** 30 * A [callbackFlow] that uses a buffer [Channel] that is "conflated" meaning that, if 31 * backpressure occurs (if the producer that emits new values into the flow is faster than the 32 * consumer(s) of the values in the flow), the values are buffered and, if the buffer fills up, 33 * we drop the oldest values automatically instead of suspending the producer. 34 */ 35 @Suppress("EXPERIMENTAL_IS_NOT_ENABLED") 36 @OptIn(ExperimentalTypeInference::class, ExperimentalCoroutinesApi::class) 37 fun <T> conflatedCallbackFlow( 38 @BuilderInference block: suspend ProducerScope<T>.() -> Unit, 39 ): Flow<T> = callbackFlow(block).buffer(capacity = Channel.CONFLATED) 40 } 41