小编Dew*_*eed的帖子

什么时候使用 Kotlin 的 suspend 关键字?

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

fun asyncFunc1() { ... }
suspend fun asyncFunc2() { ... }
Run Code Online (Sandbox Code Playgroud)

我可以在没有的情况下完成工作suspend,它甚至使测试更容易(它可以在不添加runBlocking.

我的问题:

  1. asyncFunc1vs asyncFunc2,哪个更好,为什么?
  2. 如果asyncFunc2更好,我应该suspend在协程中运行函数时总是使用吗?

更新

在最近的科特林协同程序的版本中,我注意到,如果方法不包含任何协同程序代码(如launchasync等),编译器会抱怨This inspection reports a suspend modifier as redundant if no other suspend functions are called inside。所以我认为suspend应该只在必须时使用。

更新2

来自谷歌的建议

kotlin kotlin-coroutines

16
推荐指数
2
解决办法
8180
查看次数

RemoteServiceException:错误的startForeground通知:java.util.ConcurrentModificationException

android.app.RemoteServiceException: Bad notification for startForeground: java.util.ConcurrentModificationException
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2204)
  at android.os.Handler.dispatchMessage(Handler.java:108)
  at android.os.Looper.loop(Looper.java:166)
  at android.app.ActivityThread.main(ActivityThread.java:7523)
  at java.lang.reflect.Method.invoke(Method.java:-2)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Run Code Online (Sandbox Code Playgroud)

我已经收到此崩溃报告已有一段时间了。看来这仅发生在Android 8.0.0上。

@Synchronized
override fun toForeground(id: Int) {
    fun action() {
        startForeground(id, builder?.build())
    }
    if (Looper.myLooper() === Looper.getMainLooper()) {
        action()
    } else {
        Handler(Looper.getMainLooper()).post { action() }
    }
}
Run Code Online (Sandbox Code Playgroud)

每个频道均已设置,并且该应用程序可以在Android 8.0.0及更高版本的设备上运行,并且在测试过程中没有任何问题,除非我无法重现崩溃。

我想知道为什么会发生此崩溃以及如何解决它。

提前致谢。

android android-service

8
推荐指数
1
解决办法
618
查看次数

Android 导航组件:如何以编程方式添加目的地?

我想为当前的导航图注入一个新的目的地。

我注意到NavGraph有一个方法,void addDestination(@NonNull NavDestination node)但我找不到正确的方法来创建一个NavDestination并使用navController.navigate(R.id.new_dest_id).

android android-jetpack android-architecture-navigation

6
推荐指数
1
解决办法
3756
查看次数