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.settingslib.spa.framework.util
18 
19 import kotlinx.coroutines.flow.Flow
20 import kotlinx.coroutines.flow.combine
21 import kotlinx.coroutines.flow.map
22 import kotlinx.coroutines.flow.take
23 
24 /**
25  * Returns a [Flow] whose values are a list which containing the results of applying the given
26  * [transform] function to each element in the original flow's list.
27  */
28 inline fun <T, R> Flow<List<T>>.mapItem(crossinline transform: (T) -> R): Flow<List<R>> =
29     map { list -> list.map(transform) }
30 
31 /**
32  * Returns a [Flow] whose values are a list which containing the results of asynchronously applying
33  * the given [transform] function to each element in the original flow's list.
34  */
35 inline fun <T, R> Flow<List<T>>.asyncMapItem(crossinline transform: (T) -> R): Flow<List<R>> =
36     map { list -> list.asyncMap(transform) }
37 
38 /**
39  * Returns a [Flow] whose values are a list containing only elements matching the given [predicate].
40  */
41 inline fun <T> Flow<List<T>>.filterItem(crossinline predicate: (T) -> Boolean): Flow<List<T>> =
42     map { list -> list.filter(predicate) }
43 
44 /**
45  * Delays the flow a little bit, wait the other flow's first value.
46  */
47 fun <T1, T2> Flow<T1>.waitFirst(otherFlow: Flow<T2>): Flow<T1> =
48     combine(otherFlow.take(1)) { value, _ -> value }
49