Kotlin coroutines return String


#1

I am trying to convert a method from java to kotlin and replace AsynchTask with coroutines, but I do not know how to return value from coroutines

This is my method

    override fun getCompressedVideo(context:Context ,video: Uri) {

            GlobalScope.launch(Dispatchers.Main) {

                val inputFile = video.getRealPathFromVideoUri(context)
                val loadJNI: LoadJNI = LoadJNI();
                try {

                    val workFolder: String = context.filesDir.absolutePath

                    val outputFile: String = getFileFullName(
                        FilesConstants.VIDEO_FOLDER,
                        String.format(FilesConstants.VIDEO_NAME_FILE_FORMAT, System.currentTimeMillis())
                    );

                    val complexCommand = arrayOf (
                        "ffmpeg", "-y"
                        , "-i", inputFile
                        , "-strict", "experimental"
                        , "-s", "320x240"
                        , "-r", "25"
                        , "-aspect", "4:3"
                        , "-ab", "48000"
                        , "-ac", "2"
                        , "-vcodec", "mpeg4"
                        , "-movflags", "+faststart"
                        , "-ar", "22050"
                        , "-b", "2097k"
                        , outputFile);

                    loadJNI.run(complexCommand, workFolder, context);
                    return outputFile

                } catch (th: Throwable) {
                    return@launch
                }
            }
        }

the line of return outputFile make compilation error , can anyone please help, it is my first time to use coroutines


#2

You cannot use return

https://kotlinlang.org/docs/reference/returns.html#return-at-labels

You have to use async

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html

Finally, you should reconsider the Dispatchers.


#3

If multiple tasks have to happen in parallel and final result depends on completion of both of them, then use async.

Otherwise, for returning the result of a single task, use withContext.