首页 > 解决方案 > 如何使用 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来做到这一点?

标签: androidbitmapviewmodelandroid-lifecycleandroid-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
        })

}

推荐阅读