开始使用 kotlin 和 SpringBootApplication 运行 一些暂停的乐趣

getting started with kotlin and SpringBootApplication to run some suspend fun

尝试 运行 这个 repo 有一些暂停功能。有人可以给一些提示吗?

假设我们有一个

suspend fun log(){
        mLog.subscribeAlways<GroupMessageEvent> { event ->
        if (event.message.content.contains("Error")) {
            print("****")


        } else if (event.message.content.contains("Warning")) {
            print("Warning")
        }
    }

    mLog.Listen()  
    
  }

我们如何从 main

触发这个日志
open class Application {


    companion object {
        @JvmStatic fun main(args: Array<String>) {

            SpringApplication.run(Application::class.java, *args)

        }    
    }
}

什么都试过了,可以运行没有报错,但是没有按预期工作, 从 Controller class

调用日志函数
class Controller {

    @Value("${spring.datasource.url}")
    private var dbUrl: String? = null

    @Autowired
    lateinit private var dataSource: DataSource
   
    @RequestMapping("/")
     internal suspend fun index(): String {
         mLog()
        return "index"
    }

Suspend functions should be called from a coroutine. There are several coroutine builder functions: launch, async, runBlocking。 使用这些函数你可以启动一个协程,例如:

runBlocking { 
    // call suspend methods
}

在某些 CoroutineScope. They don't block the current thread. There are more info in the docs.

的上下文中使用 launchasync 协程构建器启动协程

runBlocking 中断地阻塞当前线程直到它完成。

使用 launch 协程构建器,如果在其中调用 suspend 函数,您将不会阻塞当前线程:

fun index(): String {
    GlobalScope.launch {
        log()
    }
    "index"
}

注意:在这种情况下函数index returns在log执行之前。 GlobalScope. Application code usually should use an application-defined CoroutineScope. How to define a CoroutineScope is described in the docs and and .

如果您打算阻塞当前线程,直到 suspend 函数完成,请使用 runBlocking 协程构建器:

fun index(): String = runBlocking {
    log()
    "index"
}

一些有用的链接:GlobalScope.launch vs runBlocking, , .