Question

The example code is from here:

def http_get(url)
  f = Fiber.current
  http = EventMachine::HttpRequest.new(url).get

  # resume fiber once http call is done
  http.callback { f.resume(http) }
  http.errback  { f.resume(http) }

  return Fiber.yield
end

EventMachine.run do
  Fiber.new{
    page = http_get('http://www.google.com/')
    puts "Fetched page: #{page.response_header.status}"

    if page
      page = http_get('http://www.google.com/search?q=eventmachine')
      puts "Fetched page 2: #{page.response_header.status}"
    end
  }.resume
end

So, in the context of the EM run block, the author's creating a fiber and running it immediately with resume. But, I don't understand why the http_get logic is structured in that way. I mean, it's taking the current fiber ( which in this case should be the one created in the EM run block ), it starts a http request which may fail or succeed, and it resumes the current fiber. Afterwards it just calls yield on the fiber. What exactly will be running since he is calling yield? Can someone please explain why http_get is written the way it is?

Was it helpful?

Solution

  1. Fiber is created and triggered in EventMachine
  2. the goal is (a) to fetch a page and (b) work on it
  3. the Fiber should be paused until the page is fetched, this is the role of http_get
  4. http = EventMachine::HttpRequest.new(url).get doesn't trigger anything: EventMachine needs to get the reins back, that's the role of Fiber.yield
  5. Once EventMachine has done the job getting the page, it triggers the callback and resumes the Fiber which was stopped at puts ...

Clearer?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top