Maxfield
Maxfield

Reputation: 209

getting started with kotlin and SpringBootApplication to run some suspend fun

Trying to run this repo with some suspend functions. Can someone please give some hints?

Let say we have one

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()  
    
  }

How can we trigger this log from main

open class Application {


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

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

        }    
    }
}

What have try, it can run without error, but it didn't work as expected, call the log function from 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"
    }

Upvotes: 1

Views: 1190

Answers (1)

Sergio
Sergio

Reputation: 30585

Suspend functions should be called from a coroutine. There are several coroutine builder functions: launch, async, runBlocking. Using these functions you can start a coroutine, for example:

runBlocking { 
    // call suspend methods
}

Coroutines launched with launch and async coroutine builders in a context of some CoroutineScope. They don't block the current thread. There are more info in the docs.

runBlocking blocks the current thread interruptibly until its completion.

Using launch coroutine builder you will not block the current thread if calling suspend function in it:

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

Note: in this case function index returns before log is executed. GlobalScope is discouraged to use. Application code usually should use an application-defined CoroutineScope. How to define a CoroutineScope is described in the docs and here and here.

If your intention is to block the current thread until suspend function completes use runBlocking coroutine builder:

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

Some useful links: GlobalScope.launch vs runBlocking, Update UI async call with coroutines, Suspend function 'callGetApi' should be called only from a coroutine or another suspend function.

Upvotes: 1

Related Questions