使用 AWS Amplify 下载多个文件 Android

Downloading multiple files using AWS Amplify for Android

我正在构建一个 Android 应用程序,它使用 AWS Amplify 从 S3 列出和下载文件。

示例代码显示下载是异步的:

Amplify.Storage.downloadFile()
    "ExampleKey",
    new File(getApplicationContext().getFilesDir() + "/download.txt"),
    result -> Log.i("MyAmplifyApp", "Successfully downloaded: " + result.getFile().getName()),
    error -> Log.e("MyAmplifyApp",  "Download Failure", error)
);

我希望在后台线程中下载(可能很多)文件,并在所有文件下载完成(或发生错误)后通知主线程。问题:

实现此功能的最佳方法是什么?

P.S。 我已经尝试了可以​​调用 blockingSubscribe()RxAmplify, which exposes RxJava Observables。但是,绑定非常新,我在使用它时遇到了一些应用程序崩溃的未捕获异常。

使用香草放大

downloadFile() 将在后台线程上执行其工作。只需使用 standard approaches 之一返回主线程,从回调:

Handler handler = new Handler(context.getMainLooper());
File file = new File(context.getFilesDir() + "/download.txt");

Amplify.Storage.downloadFile(
    "ExampleKey", file,
    result -> {
        handler.post(() -> {
            Log.i("MyAmplifyApp", "Successfully downloaded: " + result.getFile().getName());
        });
    },
    error -> Log.e("MyAmplifyApp",  "Download Failure", error)
);

有 Rx 绑定

但就个人而言,我会使用 Rx 绑定。 The official documentation 包括 Rx API 的片段。这是一个更适合的例子:

File file = new File(context.getFilesDir() + "/download.txt");
RxAmplify.Storage.downloadFile("ExampleKey", file)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(result -> {
        Log.i("RxExample", "Download OK.");
    }, failure -> {
        Log.e("RxExample", "Failed.", failure);
    });

运行 多个并行下载

通过调用 RxAmplify.Storage.downloadFile("key", local) 构建 Single 的集合。然后,使用 Single.mergeArray(...) 将它们全部组合起来。以与上述相同的方式订阅它。

RxStorageCategoryBehavior storage = RxAmplify.Storage;
Single
    .mergeArray(
        storage.downloadFile("one", localOne)
            .observeResult(),
        storage.downloadFile("two", localTwo)
            .observeResult()
    )
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(/* args ... */);

报告错误

您提到您遇到了意外异常。如果是这样,请提交错误 here,我会修复它。