Using Fiber
What is Fiber?
Ruby provides a class called Fiber for working with coroutines.
A coroutine is a mechanism that allows you to pause execution and later resume it from where it left off.
In some languages, asynchronous operation using async/await
are referred to as coroutines.
However, Ruby's Fiber
uses yield
and resume
to pause and resume execution.
To create a Fiber, use Fiber.new
.
Note that simply calling Fiber.new
does not start execution.
Let's try it out using the REPL.
@fiber = Fiber.new do
Godot.emit_signal :fiber, 'started'
Fiber.yield
Godot.emit_signal :fiber, 'resumed'
end
=> "#<Fiber:0x1ab31c76030 (created)>"
To start execution, call resume
.
@fiber.resume
[ fiber ] signal emitted: 'started'
=> <null>
When Fiber.yield
is called, execution is paused at that point.
To resume, call resume
again.
@fiber.resume
[ fiber ] signal emitted: 'resumed'
=> true
Fiber.yield Arguments and Return Values
The arguments passed to Fiber.yield
will be returned when resume
is called.
@fiber = Fiber.new do
value = Fiber.yield 'started'
Godot.emit_signal :fiber, value
end
@fiber.resume
=> "started"
The arguments passed to resume
become the return values of Fiber.yield
.
@fiber.resume 'hello'
[ fiber ] signal emitted: "hello"
=> true
By using coroutines, you can pause and resume execution at arbitary points—making it possible to build systems like a dialogue system.
In the next chapter, we'll build a dialogue system example using Fiber.