1 /* 2 * Copyright 2023 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 androidx.compose.foundation.lazy.layout 18 19 import androidx.compose.ui.layout.LayoutCoordinates 20 import androidx.compose.ui.layout.OnGloballyPositionedModifier 21 import androidx.compose.ui.util.fastForEach 22 import kotlin.coroutines.Continuation 23 import kotlin.coroutines.resume 24 import kotlinx.coroutines.suspendCancellableCoroutine 25 26 /** 27 * Internal modifier which allows to delay some interactions (e.g. scroll) until layout is ready. 28 */ 29 internal class AwaitFirstLayoutModifier : OnGloballyPositionedModifier { 30 private var wasPositioned = false 31 private val continuations = mutableListOf<Continuation<Unit>>() 32 waitForFirstLayoutnull33 suspend fun waitForFirstLayout() { 34 if (!wasPositioned) { 35 var continuation: Continuation<Unit>? = null 36 try { 37 suspendCancellableCoroutine<Unit> { 38 continuation = it 39 continuations.add(it) 40 } 41 } finally { 42 continuations.remove(continuation) 43 } 44 } 45 } 46 onGloballyPositionednull47 override fun onGloballyPositioned(coordinates: LayoutCoordinates) { 48 if (!wasPositioned) { 49 wasPositioned = true 50 continuations.fastForEach { it.resume(Unit) } 51 continuations.clear() 52 } 53 } 54 } 55