Is it okay to return `State` type from composables...
# compose
m
Is it okay to return
State
type from composables in this way? In this particular case, I’m waiting for window focus before reading the clipboard (it won’t work on Android otherwise). I only use this on app launch so I’m not looking to monitor changes in the clipboard, but just wait for the first state value:
Copy code
@Composable
fun clipTextState(): State<String?> {
    val clipTextState: MutableState<String?> = rememberSaveable {
        mutableStateOf(null)
    }
    WindowFocusObserver { isWindowFocused ->
        if (isWindowFocused) {
            clipTextState.value = /* readClipText */
        }
    }
    return clipTextState
}
w
What's your goal? I think a more common approach is to accept
onClipAvailable: (String?) -> Unit
, rememberUpdatedState it, and then invoke it in the observer. The caller can then react to that event however it wants.
m
I’m processing incoming intents to produce UI state of what to do next (e.g. show dialog, show message, launch main app). Unfortunately, to generate the state for a read-clipboard intent, I need to use compose to get the clip text, because what I would ideally want is to first read the text before feeding it back into the pipeline to generate the more appropriate UI state (i.e. as if that text had been passed in explicitly in the intent).
This seems to be more along the lines of existing APIs (note: I need to call a suspending fun to process the text)
Copy code
@Composable
fun LaunchedClipboardReaderEffect(
    processClipText: suspend CoroutineScope.(String) -> Unit,
) {
    var clipText: String? by remember {
        mutableStateOf(null)
    }
    LaunchedEffect(clipText) {
        clipText?.let { text ->
            processClipText(text)
        }
    }
    WindowFocusObserver { isWindowFocused ->
        if (isWindowFocused && clipText == null) { // make sure we don't set more than once
            clipText = /* readClipText as non-null String */
        }
    }
}