I want to cancel a function after a timeout on android with kotlin coroutines but it doesn’t work

What I want to do is to translate a list of texts with google cloud translation which is works but sometimes it is very slow. So after 10 seconds I want to cancel it and with withTimeoutOrNull block but it doesn’t cancel the operation it keeps running even after the timeout.

  lifecycleScope.launch {
                withContext(Dispatchers.IO) {   
     var imageClassesListInHungarian = listOf<String>()
                        withTimeoutOrNull(10000) {
                            imageClassesListInHungarian = translateList(
                                imageClassesList,
                                "hu",
                                resources
                            )
                        }  // cannot be cancelled but I don't know why
            
                  ...
             } 
    }



fun translateList(originalTextsList: List<String>, targetLanguage: String, resources: Resources): List<String> {
        val translatedTextsList = mutableListOf<String>()
        try {
            val translate = getTranslateService(resources)
            val translation = translate?.translate(originalTextsList, Translate.TranslateOption.targetLanguage(targetLanguage), Translate.TranslateOption.model("base"))
            if (translation != null) {
                for(t in translation) {
                    translatedTextsList.add(t.translatedText)
                }
            }
        }
        catch (e: TranslateException) {
            e.printStackTrace()
        }
        return translatedTextsList
    }

Source: Android Questions

LEAVE A COMMENT