establishTextInputSession
suspend fun PlatformTextInputModifierNode.establishTextInputSession(
block: suspend PlatformTextInputSessionScope.() -> Nothing
): Nothing
Starts a new text input session and suspends until the session is closed.
The block
function must call PlatformTextInputSession.startInputMethod
to actually show and
initiate the connection with the input method. If it does not, the session will end when this
function returns without showing the input method.
If this function is called while another session is active, the sessions will not overlap. The
new session will interrupt the old one, which will be cancelled and allowed to finish running any
cancellation tasks (e.g. finally
blocks) before running the new block
function.
The session will be closed when:
- The session function throws an exception.
- The requesting coroutine is cancelled.
- Another session is started via this method, either from the same modifier or a different one. The session may remain open when:
- The system closes the connection. This behavior currently only exists on Android depending on OS version. Android platform may intermittently close the active connection to immediately start it back again. In these cases the session will not be prematurely closed, so that it can serve the follow-up requests.
This function should only be called from the modifier node's
coroutineScope
. If it is not, the session will not
automatically be closed if the modifier is detached.
Parameters
block | A suspend function that will be called when the session is started and that must call PlatformTextInputSession.startInputMethod to actually show and initiate the connection with the input method. |
Code Examples
platformTextInputModifierNodeSample
@Suppress("UnusedReceiverParameter")
fun platformTextInputModifierNodeSample() {
class PlatformTextInputModifierNodeSample :
Modifier.Node(), FocusEventModifierNode, PlatformTextInputModifierNode {
private var focusedJob: Job? = null
override fun onFocusEvent(focusState: FocusState) {
focusedJob?.cancel()
focusedJob =
if (focusState.isFocused) {
// establishTextInputSession is a suspend function, so it must be called from a
// coroutine. Launching it into this modifier node's coroutine scope ensures the
// session will automatically be torn down when the node is detached.
coroutineScope.launch {
// This will automatically cancel any currently-active session.
establishTextInputSession {
launch {
// TODO: Observe text field state, call into system to update it as
// required by the platform.
}
// Call out to a platform-specific expect/actual function to create the
// platform-specific request.
val request: PlatformTextInputMethodRequest = createInputRequest()
startInputMethod(request)
}
}
} else {
null
}
}
// This would probably be an expect/actual function.
fun PlatformTextInputSession.createInputRequest(): PlatformTextInputMethodRequest {
TODO("Create platform-specific request")
}
}
}