Search code examples
kotlinkotlinx.coroutines

How to trigger a function onAwait of a CompletableDeferred<String>?


I'm trying to index an image when it is created. I thought it would be as easy as:

val saveLocation = CompletableDeferred<String>()
saveLocation.onAwait { loc:String ->
    MediaScannerConnection.scanFile(applicationContext, arrayOf(loc), null, null)
}

But it says Expression onAwait of type SelectClause1<String> cannot be invoked as a function so maybe I'm using it wrong? Is there a way to register a function to be called when the CompletableDeferred finishes?


Solution

  • onAwait is a property which returns SelectClause1<T>

    So you would use something like this

    val clause = saveLocation.onAwait
    clause.registerSelectClause1( // your args here)
    

    But, if you want the result of the deferred why don't you just start a coroutine and call await?

    launch {
      val result = saveLocation.await()
      MediaScannerConnection.scanFile(applicationContext, arrayOf(result), null, null)
    }