Utils.kt (2722B)
1 /* 2 * This file is part of GNU Taler 3 * (C) 2022 Taler Systems S.A. 4 * 5 * GNU Taler is free software; you can redistribute it and/or modify it under the 6 * terms of the GNU General Public License as published by the Free Software 7 * Foundation; either version 3, or (at your option) any later version. 8 * 9 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 * A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along with 14 * GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 package net.taler.wallet.compose 18 19 import androidx.compose.foundation.layout.padding 20 import androidx.compose.material3.Surface 21 import androidx.compose.runtime.Composable 22 import androidx.compose.runtime.State 23 import androidx.compose.runtime.collectAsState 24 import androidx.compose.runtime.remember 25 import androidx.compose.ui.Modifier 26 import androidx.compose.ui.input.nestedscroll.nestedScroll 27 import androidx.compose.ui.platform.LocalLifecycleOwner 28 import androidx.compose.ui.platform.rememberNestedScrollInteropConnection 29 import androidx.compose.ui.unit.dp 30 import androidx.lifecycle.Lifecycle 31 import androidx.lifecycle.LifecycleOwner 32 import androidx.lifecycle.flowWithLifecycle 33 import kotlinx.coroutines.flow.Flow 34 import kotlinx.coroutines.flow.StateFlow 35 import kotlin.coroutines.CoroutineContext 36 import kotlin.coroutines.EmptyCoroutineContext 37 38 @Composable 39 fun <T> rememberFlow( 40 flow: Flow<T>, 41 lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, 42 ): Flow<T> = remember(key1 = flow, key2 = lifecycleOwner) { 43 flow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED) 44 } 45 46 @Composable 47 fun <T : R, R> Flow<T>.collectAsStateLifecycleAware( 48 initial: R, 49 context: CoroutineContext = EmptyCoroutineContext, 50 ): State<R> { 51 val lifecycleAwareFlow = rememberFlow(flow = this) 52 return lifecycleAwareFlow.collectAsState(initial = initial, context = context) 53 } 54 55 @Suppress("StateFlowValueCalledInComposition") 56 @Composable 57 fun <T> StateFlow<T>.collectAsStateLifecycleAware( 58 context: CoroutineContext = EmptyCoroutineContext, 59 ): State<T> = collectAsStateLifecycleAware(initial = value, context = context) 60 61 fun Modifier.safeHorizontalPadding(): Modifier = 62 then(Modifier.padding(horizontal = 14.dp)) 63 64 fun Modifier.cardPaddings(): Modifier = 65 then(Modifier.padding(horizontal = 14.dp, vertical = 7.dp)) 66 67 @Composable 68 fun TalerSurface(content: @Composable () -> Unit) { 69 Surface(Modifier.nestedScroll(rememberNestedScrollInteropConnection())) { 70 content() 71 } 72 }