I am getting an error
In src\cml\event.cr:67:18
67 | def initialize(@events : Array(Event))
^------
Error: instance variable '@events' of ChooseEvent must be Array(Event), not Array(ReceiveEvent(String))
with the following code
# Event class
abstract class Event(T)
abstract def sync : T
end
class SendEvent(T) < Event(T)
def initialize(@channel : Channel(T), @value : T)
end
def sync : T
@channel.send(@value)
@value
end
end
# Receive event
class ReceiveEvent(T) < Event(T)
def initialize(@channel : Channel(T))
end
def sync : T
@channel.receive
end
end
class ChooseEvent(T) < Event(T)
def initialize(@events : Array(Event(T)))
end
def sync : T
# Create a buffered channel with capacity 1
result_channel = Channel(T).new
# Use a synchronized mechanism to ensure only one result
done = Channel(Nil).new
# Create a fiber for each event
@events.map do |event|
spawn do
begin
result = event.sync
# Try to send the result, but only if no result has been sent yet
select
when result_channel.send(result)
done.send(nil)
else
# If send fails (channel is full), do nothing
nil
end
rescue ex
# Optionally log the exception
# puts "Event failed: #{ex.message}"
end
end
end
# Wait for the first result
select
when result = result_channel.receive
result
when done.receive
# Synchronization point
result_channel.receive
end
end
end