1
votes

I have a runnable jar that has a UI made with javafx fxml and the class code in kotlin with some database operations done with spring jpa.

Everything works great, except that I would like to not block the main thread while doing the work. Coming from C# I saw that in kotlin you can use coroutine like async await.


import javafx.fxml.FXML
import javafx.scene.control.Button
import kotlinx.coroutines.*

class appGui{
    @FXML
    private var buttonExecute: Button? = null

    @FXML
    fun buttonExecuteClick() {
       buttonExecute!!.isDisable = true

       CoroutineScope(Dispatchers.Main).launch {
           withContext(Dispatchers.IO){
               work()
           }

           buttonExecute!!.isDisable = false
       }
    }

    private suspend fun work() {
       println("corotine starting...")
       delay(5000);
       //springMain.applyChanges()
       println("corotine finished...")
    }
}

So I have added the coroutine call, but I got an exception Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher

Looking at this exception, I found that you have to import the coroutines-android instead of the core, so I change my pom to it

        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-coroutines-android</artifactId>
            <version>1.4.2</version>
        </dependency>

which cause other exception ClassNotFoundException: android.os.Looper Now I'm confused, is the coroutine intended to be used in android app? I'm running a jar on windows. Or do I need to go back to runnable task and do things like it was done in swing?

1
If you are not running on Android you should not use the Android dependency. Maybe this helps: github.com/Kotlin/kotlinx.coroutines/blob/master/ui/… - mipa
mipa, that is it! So simple, I have just changed the import from kotlinx-coroutines-android to kotlinx-coroutines-javafx thanks! - P. Waksman

1 Answers

2
votes

Thank to mipa (comment) for the tip.

just change the pom to import the javafx instead android.

        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-coroutines-javafx</artifactId>
            <version>1.4.2</version>
        </dependency>

simple and easy.

There is 3 main imports in the doc right now https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md

  • kotlinx-coroutines-android -- Dispatchers.Main context for Android applications.
  • kotlinx-coroutines-javafx -- Dispatchers.JavaFx context for JavaFX UI
  • applications. kotlinx-coroutines-swing -- Dispatchers.Swing context for Swing UI applications.

I just need to use the right one