android - 如何使用 ViewModel 存储位图列表以便在生命周期更改中生存?
问题描述
我正在尝试使用以下代码从InputStream加载位图列表后将其存储到List < Bitmap >中。
URL url = new URL(img_url);
InputStream inputStream = url.openConnection().getInputStream();
if (inputStream != null) {
trailerPicBitmaps.add(BitmapFactory.decodeStream(inputStream));
}
因此,现在使用AsyncTaskLoader加载所有图像后,我将其保存在List < Bitmap > bitmapList中。如何保存它以便应对配置更改。我使用了onSaveInstanceState但是当我导航到另一个应用程序时应用程序崩溃了。
无论如何使用ViewModel来做到这一点?
解决方案
好的,所以你可以这样做:
首先,您将保留位图(viewModel)的地方。
private val bitmapStore = MutableLiveData<List<Bitmap>>()
现在要获得它,您应该使用(viewModel):
fun getBitmaps() = bitmapStore
在片段中onActivityCreated
,例如setupUi
放置您的可观察对象:
viewModel.getBitmaps().observe(this, Observer {
//show bitmaps somewhere
})
并将位图放置在您的 MutableLiveData (viewModel) 中:
fun updateBitmaps(bitmaps:List<Bitmap>){
bitmapStore.postValue(bitmaps)
}
如果放置后会有一些编辑(应该在将数据存储到 MutableLiveData 之前更改数据),您应该考虑使用Transformations.switchMap
Update
从服务器接收数据的示例(如果您想将其存储在数据库中,您应该检查房间和存储库模式)。
fun fetchBitmaps(){
apiServices.fetchBitmaps()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateBitmaps(it)
}, { throwable ->
//on error
})
}
推荐阅读
- reactjs - ReactJS - 无法从导致错误的 api 中找到最新标题
- c# - 为什么 RemoveRange 在已被跟踪的实体上失败?
- scope - 为什么我在 Julia 宏中得到 UndefVarError
- python - 填充一个轮廓的圆圈
- java - E/SchedPolicy:set_timerslack_ns 写入失败:不允许操作
- php - 如何检查循环中的表单元素?
- android - 视频落后于安装在树莓派 3 上的 android
- c++ - 递归如何获得先前的值?
- c++ - C++ 如何在 MFC 中打开 .docx 文件
- android - 屏幕开启后的 Android 视图可见性