Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android coroutine job changed to CompletableJob?

When I update my project coroutines to the newer version all my job creation with launch scope are failing...

on gradle:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'

The error:

Type mismatch: inferred type is Job but CompletableJob was expected

Code:

var websiteCrawlerResultList: ArrayList<WebsiteCrawlerResult> = arrayListOf()
    var url: URL? = null
    private var urlList: MutableSet<String> = mutableSetOf()
    private var job = Job()
    private var scope = CoroutineScope(Dispatchers.Default+job)

    fun startCrawler() {
        job = scope.launch {
            crawlPageLinks(url)
            Log.d(TAG, "Finished ${url.toString()} crawling")
        }
    }

when job = scope.launch { Android Studio return the type mismatch error, he expect to be CompletableJob, but I not using it and this don't exists on the old version.

like image 639
felipe.rce Avatar asked Jan 25 '23 13:01

felipe.rce


1 Answers

Job() is actually a factory function that returns a CompletableJob. Therefore the type of private var job = Job() is CompletableJob. However, the return type for scope.launch is just a Job. You get an error because not all Job instances are CompletableJob instances.

Instead of relying on type inference (and the automatically assigned CompletableJob type), you can specify the exact type you want to use:

private var job: Job = Job()
like image 53
ianhanniballake Avatar answered Feb 11 '23 18:02

ianhanniballake