我正在使用 android 架构组件,rxjava 和 mvvm 结构改造,顺便说一句,我是这些领域的新手
我遇到的问题是,我在 viewmodel 中处理了我的一次性用品,问题是这样的,当我从一个 Activity 转到另一个 Activity 或关闭应用程序时它会被触发并且它不会再次重新启动重新打开 Activity ,所以我失去了连接,我得到 FAILED: java.io.IOException: Canceled error when I want to use the api connection again 。
这是我的代码:
class CategoryViewModel(private val model:CategoryModel): ViewModel() {
private lateinit var catsLiveData:MutableLiveData<MutableList<Cat>>
fun getCats():MutableLiveData<MutableList<Cat>>{
if(!::catsLiveData.isInitialized){
catsLiveData=model.getCats()
}
return catsLiveData;
}
override fun onCleared() {
super.onCleared()
model.clearDisposable()
}
这是我从互联网获取数据的模型类:
class CategoryModel(
private val netManager: NetManager,
private val sharedPrefManager: SharedPrefManager) {
private lateinit var categoryDao: CategoryDao
private lateinit var dbConnection: DbConnection
private lateinit var lastUpdate: LastUpdate
private var list: MutableLiveData<MutableList<Cat>> = MutableLiveData()
public val compositeDisposable= CompositeDisposable()
fun getCats(): MutableLiveData<MutableList<Cat>> {
return getCatsOnline();
}
private fun getCatsOnline(): MutableLiveData<MutableList<Cat>> {
Log.v("this", "online ");
val getCats = ApiConnection.client.create(Category::class.java)
compositeDisposable+=getCats.getCats(sharedPrefManager.getUid(), lastUpdate.getLastCatDate())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ success ->
list += success.cats
}, { error ->
Log.v("this", "ErrorGetCats " + error.localizedMessage);
}
)
return list;
}
fun clearDisposable(){
if(!compositeDisposable.isDisposed){
compositeDisposable.dispose()
Log.v("this","disposable called");
}
}
}
这有什么问题吗?
最佳答案
处置一个复合 Material 将使它处置每一个 future 添加到它的Disposable
。将其更改为 clear
,您可以重复使用相同的 CompositeDisposable
。
fun clearDisposable(){
compositeDisposable.clear()
Log.v("this","disposable called");
}
关于安卓-java.io.IOException : Canceled when disposed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55948810/