diff --git a/README.md b/README.md index a880f4a..169bf9f 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,15 @@ Preload a Monarch screen. This will load but not enable the screen. This is usef **PARAMETERS** * ```screen_id``` (hash) - Id of the screen to preload. -* ```callback``` (function) - Optional function to call when the new screen is preloaded. +* ```callback``` (function) - Optional function to call when the screen is preloaded. + + +### monarch.unload(screen_id, [callback]) +Unload a preloaded Monarch screen. A preloaded screen will automatically get unloaded when hidden, but this function can be useful if a screen has been preloaded and it needs to be unloaded again. + +**PARAMETERS** +* ```screen_id``` (hash) - Id of the screen to unload. +* ```callback``` (function) - Optional function to call when the screen is unloaded. ### monarch.top([offset]) diff --git a/monarch/monarch.lua b/monarch/monarch.lua index d87f0ac..b9f9475 100644 --- a/monarch/monarch.lua +++ b/monarch/monarch.lua @@ -676,6 +676,39 @@ function M.preload(id, cb) screen.co = co change_context(screen) preload(screen) + log("preload() done", screen.id) + if cb then cb() end + end) + assert(coroutine.resume(co)) + return true +end + + +function M.unload(id, cb) + if M.is_busy() then + log("unload() monarch is busy, ignoring request") + return false + end + assert(id, "You must provide a screen id") + id = tohash(id) + assert(screens[id], ("There is no screen registered with id %s"):format(tostring(id))) + + if M.is_visible(id) then + log("You can't unload a visible screen") + return false + end + + local screen = screens[id] + if not screen.preloaded and not screen.loaded then + log("unload() screen is not loaded", tostring(id)) + if cb then cb() end + return true + end + local co + co = coroutine.create(function() + screen.co = co + change_context(screen) + unload(screen) if cb then cb() end end) assert(coroutine.resume(co))