57 lines
1.6 KiB
Plaintext
57 lines
1.6 KiB
Plaintext
import "pkg:/source/utils/Types.bs"
|
|
|
|
function StartAsyncTask(taskFunc as object, input as object, callback = invalid as object) as object
|
|
task = CreateAsyncTask(taskFunc, input, callback)
|
|
task.control = "RUN"
|
|
return task
|
|
end function
|
|
|
|
function CreateAsyncTask(taskFunc as object, input as object, callback = invalid as object) as object
|
|
id = StrI(rnd(2147483647), 36)
|
|
task = createObject("roSGNode", GetComponentName(taskFunc))
|
|
task.id = id
|
|
task.input = input
|
|
|
|
m[`asynctask_${id}`] = task
|
|
m[`asynctask_${id}_callback`] = callback
|
|
task.ObserveFieldScoped("state", FuncName(OnTaskState))
|
|
|
|
return task
|
|
end function
|
|
|
|
function GetComponentName(taskFunc as object) as string
|
|
if IsString(taskFunc)
|
|
return `${taskFunc}_asynctask`
|
|
end if
|
|
' NOTE: do NOT use FuncName in here.
|
|
' we use:
|
|
' return `${FuncName(taskFunc)}_asynctask`
|
|
' The app hangs on exit, and the TV crashes and restarts. I'm not kidding.
|
|
return (LCase(`${taskFunc}_asynctask`)).replace("function:", "").trim()
|
|
end function
|
|
|
|
function OnTaskState(e as object) as void
|
|
task = e.getRoSGNode()
|
|
if task.state = "init" or task.state = "run"
|
|
return
|
|
end if
|
|
|
|
task.UnobserveFieldScoped("state")
|
|
|
|
id = task.id
|
|
output = task.output
|
|
' if output is invalid, it means the task was interrupted before the result is ready
|
|
if output <> invalid
|
|
callback = m[`asynctask_${id}_callback`]
|
|
if callback <> invalid
|
|
callback(output)
|
|
end if
|
|
end if
|
|
|
|
|
|
task.input = invalid
|
|
task.output = invalid
|
|
m.delete(`asynctask_${id}`)
|
|
m.delete(`asynctask_${id}_callback`)
|
|
end function
|