https://kotlinlang.org logo
Title
p

Paulius Ruminas

09/02/2019, 4:05 PM
Hello, how can I make forEach continue even if some elements get cancelled e.g.
@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

Dominaezzz

09/02/2019, 4:08 PM
launch(NonCancellable)
?
p

Paulius Ruminas

09/02/2019, 4:09 PM
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

Dominaezzz

09/02/2019, 4:11 PM
Ah, you have to surround
supervisorScope
with `try`/
catch
or
runCatching
.
p

Paulius Ruminas

09/02/2019, 4:26 PM
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.