Skip to content

Commit

Permalink
Support providing a list of Closeable to CancellableGroup construction (
Browse files Browse the repository at this point in the history
  • Loading branch information
soywiz authored Jul 11, 2023
1 parent 895d372 commit 27548a2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
9 changes: 8 additions & 1 deletion korio/src/commonMain/kotlin/korlibs/io/lang/Closeable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,16 @@ fun CloseableCancellable(callback: (Throwable?) -> Unit): CloseableCancellable =
override fun cancel(e: Throwable) = callback(e)
}

class CancellableGroup : CloseableCancellable {
class CancellableGroup() : CloseableCancellable {
private val cancellables = arrayListOf<Cancellable>()

constructor(vararg items: Cancellable) : this() {
items.fastForEach { this += it }
}
constructor(items: Iterable<Cancellable>) : this() {
for (it in items) this += it
}

operator fun plusAssign(c: CloseableCancellable) {
cancellables += c
}
Expand Down
32 changes: 32 additions & 0 deletions korio/src/commonTest/kotlin/korlibs/io/lang/CancellableTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package korlibs.io.lang

import kotlin.test.*

class CancellableTest {
@Test
fun testCancellableGroup() {
val log = arrayListOf<String>()
val cancellable1 = Cancellable { log += "1" }
val cancellable2 = Cancellable { log += "2" }
CancellableGroup(cancellable1, cancellable2).let { group ->
assertEquals("", log.joinToString(","))
group.cancel()
assertEquals("1,2", log.joinToString(","))
log.clear()
}
CancellableGroup(listOf(cancellable1, cancellable2)).let { group ->
assertEquals("", log.joinToString(","))
group.cancel()
assertEquals("1,2", log.joinToString(","))
log.clear()
}
CancellableGroup().let { group ->
group.addCancellable(cancellable1)
group.addCancellable(cancellable2)
assertEquals("", log.joinToString(","))
group.cancel()
assertEquals("1,2", log.joinToString(","))
log.clear()
}
}
}

0 comments on commit 27548a2

Please sign in to comment.