Skip to content

kotlin.coroutines.channels.awaitClose: JobCancellationException #1762

@sellmair

Description

@sellmair

The awaitClose function currently throws a JobCancellationException if the job was canceled before calling the function.

I would have personally expected that the block passed to awaitClose { } gets executed without throwing this exception.

Sample code:

internal fun SensorManager.consumeValuesAsFlow(
    sensor: Sensor,
    measureInterval: Duration = 20L with TimeUnit.MilliSeconds
): Flow<FloatArray> {
    return callbackFlow {
        val sensorEventListener = object : SensorEventListener {
            override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
            override fun onSensorChanged(event: SensorEvent) {
                catch { offer(event.values) }
            }
        }

        registerListener(
            sensorEventListener,
            sensor,
            measureInterval[TimeUnit.MicroSeconds].toInt(),
            sensorHandler
        )
        try {
            awaitClose { unregisterListener(sensorEventListener) }
        } catch (t: Throwable) {
            Log.e("SensorManager", "consumeValuesAsFlow", t) // called with JobCancellationException
        }
    }
}

Coroutines version 1.3.3
Kotlin version 1.3.61

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsKDoc and API reference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions