1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 15:47:45 +00:00

LibThreading+Everywhere: Support returning error from BackgroundAction

This patch allows returning an `Error` from the `on_complete` callback
in `BackgroundAction`.

It also adds a custom callback to manage errors returned during its
execution.
This commit is contained in:
Lucas CHOLLET 2022-12-12 23:34:28 +01:00 committed by Linus Groh
parent 664117564a
commit 2693745336
6 changed files with 38 additions and 21 deletions

View file

@ -52,16 +52,21 @@ public:
virtual ~BackgroundAction() = default;
private:
BackgroundAction(Function<Result(BackgroundAction&)> action, Function<void(Result)> on_complete)
BackgroundAction(Function<Result(BackgroundAction&)> action, Function<ErrorOr<void>(Result)> on_complete, Optional<Function<void(Error)>> on_error = {})
: Core::Object(&background_thread())
, m_action(move(action))
, m_on_complete(move(on_complete))
{
if (on_error.has_value())
m_on_error = on_error.release_value();
enqueue_work([this, origin_event_loop = &Core::EventLoop::current()] {
m_result = m_action(*this);
if (m_on_complete) {
origin_event_loop->deferred_invoke([this] {
m_on_complete(m_result.release_value());
auto maybe_error = m_on_complete(m_result.release_value());
if (maybe_error.is_error())
m_on_error(maybe_error.release_error());
remove_from_parent();
});
origin_event_loop->wake();
@ -73,7 +78,10 @@ private:
bool m_cancelled { false };
Function<Result(BackgroundAction&)> m_action;
Function<void(Result)> m_on_complete;
Function<ErrorOr<void>(Result)> m_on_complete;
Function<void(Error)> m_on_error = [](Error error) {
dbgln("Error occurred while running a BackgroundAction: {}", error);
};
Optional<Result> m_result;
};