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

Make #unsubscribe functional when both block-based subscribers and listener objects are used #17

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
1 change: 0 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@ gem "dry-core", github: "dry-rb/dry-core", branch: "main"
group :test do
gem "rack"
end

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
Loading