Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suspending function in curly brackets #338

Closed
recursive-rat4 opened this issue Jul 20, 2023 · 4 comments
Closed

Suspending function in curly brackets #338

recursive-rat4 opened this issue Jul 20, 2023 · 4 comments

Comments

@recursive-rat4
Copy link

I have a following code with version 4.0.1

suspend fun bar(): Int

suspend fun baz() {
    logger.info("Foo ${bar()}")
}

Now that version 5.0.0 deprecates round brackets, a straight conversion doesn't work, because it loses the suspension.

    logger.info { "Foo ${bar()}" }
    // e: Suspension functions can be called only within coroutine body

Would be a recommended way to wrap the suspending call into runBlocking like this?

    logger.info { "Foo ${runBlocking { bar() }}" }
@github-actions
Copy link

Thank you for reporting an issue. See the wiki for documentation and slack for questions.

@oshai
Copy link
Owner

oshai commented Jul 20, 2023

I wouldn't use runBlocking() as it will block the thread.
if you want it to work like before it should be translated to:

val barMessage = bar()
logger.info { "Foo $barMessage" }

(There is another question here which is why a log message computation will be a suspended operation).

@recursive-rat4
Copy link
Author

I wouldn't use runBlocking() as it will block the thread.

Thanks, I overlooked this detail.

There is another question here which is why a log message computation will be a suspended operation

Mutexes, mutexes everywhere.

@ivan-osipov
Copy link

@oshai
A practical problem that if you want to log extended context and load this data from your db, the method of loading is suspendable

so, for example, now you should do something like that

if(logger.isDebugEnabled()) { // or even trace
  val extraContext = loadMoreContext() // suspend func call
  logger.debug("Oops! Here is more context $extraContext")
}

instead of something like that

logger.coDebug { "Oops! Here is more context ${loadMoreContext()}" }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants