Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support providing a list of Closeable to CancellableGroup construction #1790

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}
}
}