Spot the bug
This flow crashes with 'Flow invariant is violated'. Which line causes it?
fun readLines(file: File): Flow<String> = flow {withContext(Dispatchers.IO) {file.useLines { lines ->lines.forEach { emit(it) }}}}
Hint 1 of 1
Which line changes the coroutine context?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 2
withContext(Dispatchers.IO) {
A flow can't emit from a different context than the collector's. Remove withContext and add .flowOn(Dispatchers.IO) after the flow builder.