[英]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)
);
我希望在后台线程中下载(可能很多)文件,并在所有文件下载完毕(或发生错误)后通知主线程。 问题:
实现此功能的最佳方法是什么?
PS 我试过RxAmplify ,它公开了我可以调用blockingSubscribe()
的RxJava Observables。 但是,绑定是非常新的,我在使用它时遇到了一些应用程序崩溃的未捕获异常。
downloadFile()
将在后台线程上执行其工作。 只需使用一种标准方法将 go 从回调返回到主线程:
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 Bindings。 官方文档包含 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 ... */);
你提到你遇到了意外的异常。 如果是这样,请在此处提交错误,我会修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.