1 /* <lambda>null2 * 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.async 20 import kotlinx.coroutines.awaitAll 21 import kotlinx.coroutines.coroutineScope 22 import kotlinx.coroutines.launch 23 24 /** 25 * Performs the given [action] on each element asynchronously. 26 */ 27 suspend inline fun <T> Iterable<T>.asyncForEach(crossinline action: (T) -> Unit) { 28 coroutineScope { 29 forEach { 30 launch { action(it) } 31 } 32 } 33 } 34 35 /** 36 * Returns a list containing the results of asynchronously applying the given [transform] function 37 * to each element in the original collection. 38 */ asyncMapnull39suspend inline fun <R, T> Iterable<T>.asyncMap(crossinline transform: (T) -> R): List<R> = 40 coroutineScope { 41 map { item -> 42 async { transform(item) } 43 }.awaitAll() 44 } 45 46 /** 47 * Returns a list containing only elements matching the given [predicate]. 48 * 49 * The filter operation is done asynchronously. 50 */ asyncFilternull51suspend inline fun <T> Iterable<T>.asyncFilter(crossinline predicate: (T) -> Boolean): List<T> = 52 asyncMap { item -> item to predicate(item) } <lambda>null53 .filter { it.second } <lambda>null54 .map { it.first } 55