Skip to content

Commit

Permalink
Do not raise in #unsubscribe when a block subscriber precedes the t…
Browse files Browse the repository at this point in the history
…arget Method listener in the `#listeners` hash
  • Loading branch information
Aerdayne committed Apr 26, 2024
1 parent fa973dc commit 454f0b6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/dry/events/bus.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ def detach(listener)
listeners.each do |id, memo|
memo.each do |tuple|
current_listener, _ = tuple
next unless current_listener.is_a?(Method)

listeners[id].delete(tuple) if current_listener.receiver.equal?(listener)
end
end
Expand Down
35 changes: 35 additions & 0 deletions spec/unit/dry/events/publisher_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,41 @@ def listener.on_test_event;
end
end

describe "#unsubscribe" do
it "unsubscribes a listener" do
listener = Class.new do
attr_reader :captured

def initialize
@captured = []
end

def on_test_event(event)
captured << event[:message]
end
end.new

captured_by_block = []

publisher.subscribe(:test_event) do |event|
captured_by_block << event[:message]
end
publisher.subscribe(listener)

publisher.publish(:test_event, message: "it works")

expect(listener.captured).to eql(["it works"])
expect(captured_by_block).to eql(["it works"])

publisher.unsubscribe(listener)

publisher.publish(:test_event, message: "it works")

expect(listener.captured).to eql(["it works"])
expect(captured_by_block).to eql(["it works", "it works"])
end
end

describe "#publish" do
it "publishes an event" do
result = []
Expand Down

0 comments on commit 454f0b6

Please sign in to comment.