Skip to content

New API: ya.async() #2948

@sxyazi

Description

@sxyazi

This issue proposes adding a new ya.async() Lua API, as a complement to the existing ya.sync():

  • ya.sync() - Run sync tasks within an async context, allowing access to all states within sync context through cx.
  • ya.async() - Run async tasks within a sync context, enabling access to and use of all available async APIs.

which allows:

  • Greater interoperability between sync and async contexts, eliminating the need to exchange data via ya.emit("plugin", { "plugin-itself" }).
  • Ability to pin async, time-consuming tasks, such as executing an external command, during sync UI rendering, and composite the command's output into the UI to display its result.

Create an async task:

local task = ya.async(function()
  ya.sleep(0.5)
  return 1, 2
end)

Create an async task with arguments:

local task_with_args = ya.async(ya.sleep, 0.5)

Create an async task that completes immediately:

local task_has_done = ya.async()  -- Equal to: ya.async(function() end)

Cancel a task

task:drop()

Wait for the task to complete

local a, b = ya.wait(task)  -- a = 1, b = 2

Wait for the task with a timeout

local a, b = ya.wait(task, 0.1)  -- a = nil, b = nil
local done = task:done()         -- false

Wait for a task that may error

local task_with_error = ya.async(function()
  error("An error occurred")
  return 1 -- This line will not be reached
end)

local ok, ret = pcall(ya.wait, task_with_error) -- ok = false, ret = "An error occurred"

Example: Show current disk available space in the status bar

local cwd, du, avail = nil, ya.async(), ""
Status:children_add(function()
  if cwd == cx.active.current.cwd then
    return ui.Span(avail):fg("yellow")
  end

  du:drop()  -- Kill the previous `du` process to save resources, if it's still running
  cwd, du = cx.active.current.cwd, ya.async(function()
    local output = Command("du"):arg("."):output()
    avail = output.stdout:match("(%d+)%s+%d+%%%s")
    ui.render()
  end)
  return ui.Span(avail):fg("yellow")
end, 500, Status.RIGHT)

Credit

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions