Skip to content

Commit

Permalink
feat: added EventBus.removeAllEventHandlers, #1160
Browse files Browse the repository at this point in the history
  • Loading branch information
AlmasB committed Mar 26, 2022
1 parent 3eff0db commit 887deee
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion fxgl-core/src/main/kotlin/com/almasb/fxgl/event/EventBus.kt
Expand Up @@ -24,6 +24,8 @@ class EventBus {

private val eventHandlers = Group()

private val subscribers = arrayListOf<Subscriber>()

var isLoggingEnabled = true

/**
Expand All @@ -33,7 +35,7 @@ class EventBus {
eventHandlers.addEventHandler(eventType, eventHandler)

@Suppress("UNCHECKED_CAST")
return Subscriber(this, eventType, eventHandler as EventHandler<in Event>)
return Subscriber(this, eventType, eventHandler as EventHandler<in Event>).also { subscribers.add(it) }
}

/**
Expand All @@ -43,6 +45,13 @@ class EventBus {
eventHandlers.removeEventHandler(eventType, eventHandler)
}

fun removeAllEventHandlers() {
// some of these may have already been unsubscribed, either via [removeEventHandler] or [unsubscribe],
// but given the following is a no-op when not subscribed, there is no need to update the list
subscribers.forEach { it.unsubscribe() }
subscribers.clear()
}

/**
* Fire given [event].
* All listening parties will be notified.
Expand Down
11 changes: 11 additions & 0 deletions fxgl-core/src/test/kotlin/com/almasb/fxgl/event/EventBusTest.kt
Expand Up @@ -65,6 +65,17 @@ class EventBusTest {

eventBus.fireEvent(Event(EventType.ROOT))

assertThat(count, `is`(2))
},

Executable {
// add again and remove, but this time using removeAll
eventBus.addEventHandler(EventType.ROOT, handler)

eventBus.removeAllEventHandlers()

eventBus.fireEvent(Event(EventType.ROOT))

assertThat(count, `is`(2))
}
)
Expand Down

0 comments on commit 887deee

Please sign in to comment.