Lua LGI - Running an Async loop Without Blocking

I'm trying to run a blocking infinite loop which should run in the background of my Gtk application. It should be able to receive some data from a WebSocket which is a blocking operation and then update the GUI with the new content.

The important part here is that the blocking loop shouldn't block the GUI.

I've tried solving my problem with Gio.Async.start from LGI and cqueues as several people on IRC suggested and what I found around GitHub but everything I did still blocked the main Gtk loop.

Any ideas/examples?

4 comments · 100% upvoted · other discussions

comments

DeathProgramming

During the cqueues loop, do not use the function cq:loop; instead, use the function cq:step(0) as it will step once through the sequence with a timeout of 0. There's probably better ways to do it to repeat the loop until there's nothing to run, as well.

rfajfar [OP]

Here's the important part of the solution:

function window:on_show()
  local cq = cqueues.new()
  cq:wrap(function ()
    while true do
      local txt, opc = ws:receive()
      if txt then
        textview.buffer.text = textview.buffer.text .. "\n" .. txt
      end
    end
  end)
  timer = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1000, function()
    cq:step(0)
    return true
  end)
end