Hello, how can I make forEach continue even if so...
# coroutines
p
Hello, how can I make forEach continue even if some elements get cancelled e.g.
Copy code
@Test
    fun example() = runBlockingTest {
        val actual = mutableListOf<Int>()

        launch {
            (0..5).forEach { i ->
                supervisorScope {
                    if (i == 1) cancel()
                    actual.add(i)
                }
            }
        }

        assertEquals(listOf(0, 2, 3, 4, 5), actual)
    }
d
launch(NonCancellable)
?
p
If supervisorScope parent gets cancelled I want to cancel the job. The use case is that I'm reading messages from a queue and even if processing of one message fails I want to continue but if I cancel the worker the action procesing must cancel also.
d
Ah, you have to surround
supervisorScope
with `try`/
catch
or
runCatching
.
p
I tried with `try`/`catch` before but it didn't work because the implicit receiver of cancel() scope was not the one I wanted to cancel. I specified the receiver and it works now.