run disposable background task
Answered
Can we somehow run disposable background task?
I.e. I would like all my background tasks to be cancelled when project is closed. Would be nice to just pass Project to `ProgressManager#run()` as Disposable component for that purpose. Do we have some kind of API for that?
PS I can see bunch of ProgressManager#runProcessWithProgressAsynchronously() with Project param, not sure if it will act as Disposable... Anyway all of them marked @Deprecated.
PSS For now I've maintaining the list of all my background tasks as workaround:
private static final Map<Project, List<ProgressIndicator>> mapProject2Indicators =
new ConcurrentHashMap<>();
private static class MyBackgroundable extends Task.Backgroundable {
private @Nullable final Project project;
private @NotNull final Runnable runnable;
public MyBackgroundable(@Nullable Project project, @NotNull Runnable runnable) {
super(project, "DeepCode: Analysing Files...");
this.project = project;
this.runnable = runnable;
}
@Override
public void run(@NotNull ProgressIndicator indicator) {
mapProject2Indicators.computeIfAbsent(project, p -> new ArrayList<>()).add(indicator);
runnable.run();
mapProject2Indicators.getOrDefault(project, Collections.emptyList()).remove(indicator);
}
}
// call it from ProjectManagerListener#projectClosing
public static void cancelRunningIndicators(@NotNull Project project) {
mapProject2Indicators
.getOrDefault(project, Collections.emptyList())
.forEach(ProgressIndicator::cancel);
mapProject2Indicators.remove(project);
}
Is there any better solution?
Please sign in to leave a comment.
Artsiom,
You can make your wrapping class implement Disposable and register it with
then in the dispose method to cancel your ProgressIndicator instance.