Created
June 28, 2017 17:02
-
-
Save jonatas/3e6a8b7a1da5465d6e034b056ed616a3 to your computer and use it in GitHub Desktop.
Simple broadcast using ruby-concurrent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'concurrent-edge' | |
| class Broadcast | |
| def initialize &block | |
| @channel = {} | |
| @listener = {} | |
| instance_exec(&block) | |
| Concurrent::Channel.go { start_consumer } | |
| end | |
| def on event, &block | |
| @channel[event] = Concurrent::Channel.new | |
| @listener[event] = block | |
| end | |
| def publish event, *data | |
| @channel[event] << data | |
| end | |
| def start_consumer | |
| @channel.each do |event, channel| | |
| Thread.new(event, channel) do |evt,ch| | |
| while true | |
| if data = ~ch | |
| @listener[evt].call(*data) | |
| end | |
| end | |
| end | |
| end | |
| end | |
| end | |
| b = Broadcast.new do | |
| on 'ping' do |data| | |
| publish 'pong', Time.now, data | |
| end | |
| on 'pong' do |date, i| | |
| puts "#{i} Ponged in #{Time.now - date}" | |
| end | |
| end | |
| b.publish 'ping' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment