Why is Cliboard in Jetpack Compose suspend?

Why is Cliboard in Jetpack Compose suspend?

The ClipboardManager interface was deprecated in favor of Clipboard interface. The stated reason for deprecation is:

Use Clipboard instead, which supports suspend functions.

What actual advantages does this change bring? Is it safe to assume that functions of this interface (as provided by LocalClipboard) will execute instantly and use runBlocking?

Answer

The documentation states that:

This item can include arbitrary content like text, images, videos, or any data that may be provided through a mediator. Returned entry may contain multiple items [...].

Depending on the specific situation that may be a lot of data, and copying that from/to your app's memory will take some time.

Since the main thread should only ever be occupied for a very short amount of time (less than a frame, to prevent unresponsive or stuttering UI), making these clipboard functions suspendable allows the Clipboard to ensure a proper thread is used, making the entire operation main-safe.

That wouldn't be possible with non-suspendable functions, so the job would fall to you, the developer, to remember to move all access to the clipboard off the main thread.

I'm not sure what you mean by "will execute instantly and use runBlocking", but:

  • Yes, all suspend functions will be executed immediately the moment they are called. However, the coroutine that you use may be suspended before the function is called:

    scope.launch {
        clipboard.getClipEntry()
     }
    

    This will not be executed immediately.

  • And no, runBlocking will neither be used internally, nor should you use it in your code; actually, runBlocking should never be used in an Android app, there simply isn't a valid use case.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions