Java – Hot completion of long-running tasks

Hot completion of long-running tasks… here is a solution to the problem.

Hot completion of long-running tasks

By default, the Completable is not hot. But I’m in a situation where hot Completable is very useful: downloading and caching large sets of files:

class DownloadManager {
  Completable downloadAndCacheA();
  Completable downloadAndCacheB();
}

Completable.merge(
  downloadManager.downloadAndCacheA(),
  downloadManager.downloadAndCacheB()
).subscribe();

When the file is large, the user can leave the application and return. Therefore, client code can unsubscribe from these completions and subscribe again. One file can be downloaded, but the other is still being downloaded. But since the Completable is not hot, the download starts again.

The possible options are:

  • Productionhot Completable
  • Use a hot Observer that returns Object.
  • Only Thread instances with custom Completables are used, which interact with each other.

Not very fond of all these solutions for different reasons. Is there a better way to support long-running, achievable tasks?

Solution

Using cache, suggested by akarnokd, is probably the easiest approach.

public Completable downloadAndCache() {
   if (completable == null) {
          completable = Completable.fromAction(this::syncDownloadAndCache)
                                   .cache();
   }
   return completable;
}

Related Problems and Solutions