Last active
October 31, 2019 15:19
-
-
Save choallin/4469b54dce3be8b5eab8f2a10a348d33 to your computer and use it in GitHub Desktop.
Event loop with callback register class
This file contains 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
class CallbackRegister | |
def initialize | |
@callbacks = {read: [], write: []} | |
end | |
def each(type, &block) | |
@callbacks[type].each do |callback| | |
yield callback | |
end | |
end | |
def push(callback, type) | |
@callbacks[type] << callback | |
end | |
end | |
big_file = "network/path/big_file.xlsx" | |
file_handler = open(big_file) | |
files_to_look_after = [file_handler] | |
# Before we start the event loop we get our register class | |
# from container manager, possibly something like | |
# https://dry-rb.org/gems/dry-container/0.8/ | |
register = get_callback_register_from_container_manager | |
# Event loop | |
loop do | |
puts "(Re)Starting the Event loop" | |
readable, _writeable = IO.select files_to_look_after, [], [], 0.01 | |
# 2. Step: Handle readable connection | |
if readable | |
readable.each do |ready_io| | |
# We will read 4096 bytes in each iteration | |
read_data = ready_io.read_nonblock(4096) | |
# 3. Step: Process data according to business logic | |
register.each(:read) do |callback| | |
# Here we can prepocess something if need then we | |
# call our callback | |
callback.call(ready_io, read_data) | |
# Again, we can do something after the callback | |
# is finished | |
end | |
rescue EOFError => e | |
files_to_look_after.reject! {|file| file == ready_io } | |
end | |
end | |
break if files_to_look_after.empty? | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment