本文介绍了何时使用Kotlin暂停关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fun startAsyncFunc() {
  launch {
    asyncFunc1()
    asyncFunc2()
  }
}

fun asyncFunc1() { ... }
suspend fun asyncFunc2() { ... }

我可以不用suspend来完成工作,它甚至可以使测试变得更加容易(可以在不添加runBlocking的情况下进行测试.

I can finish the work without suspend and it even makes test easier (it can be tested without adding runBlocking.

我的问题:

  1. asyncFunc1 vs asyncFunc2,哪个更好,为什么?
  2. 如果asyncFunc2更好,那么只要在协程中运行函数,我是否应该始终使用suspend?
  1. asyncFunc1 vs asyncFunc2, which is better and why?
  2. If asyncFunc2 is better, should I always use suspend whenever a function will be ran in the coroutines?

更新

在Kotlin Coroutines的最新版本中,我注意到一个方法是否不包含任何协程代码(例如launchasync等),编译器会抱怨This inspection reports a suspend modifier as redundant if no other suspend functions are called inside.因此,我认为suspend仅在必须时使用.

Update

In the recent releases of Kotlin Coroutines, I notice if a method doesn't contain any coroutines code(like launch, async, etc), the compiler complains This inspection reports a suspend modifier as redundant if no other suspend functions are called inside. So I assume that suspend should be only used when it's a must.

Google的建议

推荐答案

仅在需要时声明函数suspend.我会说,如果有疑问,如果编译器不强迫您,请不要使用suspend.

You should only declare your function suspend if it needs to. I would say that, when in doubt, if the compiler does not force you, don't use suspend.

大多数时候,如果您有充分的理由要暂停函数,则意味着它正在做某事,可能仍然需要您使用withContext之类的暂停函数,这将迫使您声明函数suspend.

Most of the time, if you have a good reason for your function to be suspending, it means it's doing something that probably requires you to use suspending functions like withContext anyway, and this will force you to declare your function suspend.

请注意,声明函数suspend不会使调用者做的事情比未暂停函数时要多.如果有的话,就限制了函数的使用.

Note that declaring a function suspend does not enable your callers to do anything more than they could when your function was not suspending. If anything, you're limiting the use of your function.

我相信一个无需暂停就挂起函数的用例是,当您真正绝对要向世人展示您的函数在计算上很繁重,从而迫使调用者应对挂起时.

I believe one use case for a function to be suspending without being forced to is when you really absolutely positively want to show the world that your function is computationally heavy, and thus force your callers to deal with the suspension.

这篇关于何时使用Kotlin暂停关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:37