Android 如何从活动中的API调用的ViewModel中获取错误?

Android 如何从活动中的API调用的ViewModel中获取错误?,android,mvvm,rx-java2,rx-android,android-viewmodel,Android,Mvvm,Rx Java2,Rx Android,Android Viewmodel,在Android中使用ViewModel时,我在ViewModel类中使用了两个可变的LiveData对象 var imageList: MutableLiveData<List<HitsItem>> = MutableLiveData() var errorMessage: MutableLiveData<String> = MutableLiveData() var-imageList:MutableLiveData=MutableLiveData()

在Android中使用ViewModel时,我在ViewModel类中使用了两个可变的LiveData对象

var imageList: MutableLiveData<List<HitsItem>> = MutableLiveData()
var errorMessage: MutableLiveData<String> = MutableLiveData()
var-imageList:MutableLiveData=MutableLiveData()
var errorMessage:MutableLiveData=MutableLiveData()
我想要的是,每当设置API调用errorMessage时发生错误,同样,当API调用成功时,设置imageList

如何检查API在活动中是否成功,当API调用未成功时,我希望在活动中显示Toast错误消息

ImageViewModel.kt

fun getImages(): LiveData<List<HitsItem>> {
    imageList = MutableLiveData()
    loadImages()
    return imageList
}

fun loadImages() {
    val api = PexelClient.getClient().create(ApiInterface::class.java)
    val imageObservable = api.images
    imageObservable.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .map({ result -> result })
        .subscribe(
            Consumer<ImageModel> { this.handleResults(it) },
            Consumer<Throwable> { this.handleError(it) }
        )
}

private fun handleResults(list: ImageModel) {
    imageList.value = list.hits
    errorMessage.value = null
}

private fun handleError(t: Throwable) {
    imageList.value = null
    errorMessage.value = t.message
}
fun getImages():LiveData{
imageList=MutableLiveData()
loadImages()
返回图像列表
}
趣味加载图像(){
val api=PexelClient.getClient().create(apinterface::class.java)
val imageObservable=api.images
imageObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map({result->result})
.订阅(
消费者{this.handleResults(it)},
消费者{this.handleError(it)}
)
}
私人娱乐手册结果(列表:ImageModel){
imageList.value=list.hits
errorMessage.value=null
}
私人娱乐手柄错误(t:可丢弃){
imageList.value=null
errorMessage.value=t.message
}
活动

lateinit var imagesViewModel:ImagesViewModel
lateinit var adapter:ImageAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_mvvm_rx_retrofit)


    rv_images.setHasFixedSize(true)
    rv_images.layoutManager = LinearLayoutManager(this)

    imagesViewModel = ViewModelProviders.of(this).get(ImagesViewModel::class.java)
    imagesViewModel.getImages().observe(this, object : Observer<List<HitsItem>> {
        override fun onChanged(imageList: List<HitsItem>?) {
            if(imageList != null){
                adapter = ImageAdapter(this@MvvmRxRetrofit,imageList)
                rv_images.adapter = adapter
            }
        }
    })


}
lateinit var imagesViewModel:imagesViewModel
lateinit变量适配器:ImageAdapter
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\U mvvm\U rx\U改装)
rv_图像。setHasFixedSize(真)
rv_images.layoutManager=LinearLayoutManager(此)
imagesViewModel=ViewModelProviders.of(this.get)(imagesViewModel::class.java)
imagesViewModel.getImages().observe(此,对象:Observer{
更改后覆盖乐趣(imageList:List?){
如果(imageList!=null){
适配器=图像适配器(this@MvvmRxRetrofit,图像列表)
rv_images.adapter=适配器
}
}
})
}
  • 创建网络响应类
  • 公共类异步响应{

    public ResponseStatus responseStatus ;
    public Throwable error ;
    public JsonElement data ;
    
    
    AsyncResponse(ResponseStatus responseStatus, JsonElement data ,Throwable error){
        this.responseStatus = responseStatus ;
        this.data = data ;
        this.error = error ;
    }
    
    public static AsyncResponse loading(){
        return new AsyncResponse(ResponseStatus.LOADING,null,null);
    }
    
    public static AsyncResponse success(JsonElement data){
        return new AsyncResponse(ResponseStatus.SUCCESS,data,null);
    }
    
    public static AsyncResponse error(Throwable error){
        return new AsyncResponse(ResponseStatus.ERROR,null,error);
    }
    
    }

  • 创建枚举类

    公共枚举响应状态{ 加载、成功、错误 }

  • 在viewmodel类中,无论您在哪里收到响应,只要发布值:

    私有可变LiveData异步响应表LiveData =新的可变LiveData()

    响应成功:

    AsyncResponse表LiveData.postValue(AsyncResponse.success())

    响应错误:

    AsyncResponseUMatableLiveData.postValue(AsyncResponse.error(新的Throwable(e))

  • 4。在活动课上,观察反应

     mChatDialogViewModel.getResponse().observe(this, new Observer<AsyncResponse>() {
                @Override
                public void onChanged(@Nullable AsyncResponse asyncResponse) {
                    if (asyncResponse != null)
                        consumeResponse(asyncResponse);
                }
            });
    
    private void consumeResponse(AsyncResponse asyncResponse) {
    
            switch (asyncResponse.responseStatus) {
    
                case LOADING: {
                    break;
                }
                case SUCCESS: {
    
                    break;
                }
                case ERROR: {
    
                    break;
                }
                default:
                    break;
    
            }
    
    mChatDialogViewModel.getResponse().observe(这是新的观察者(){
    @凌驾
    已更改公共void(@Nullable AsyncResponse){
    if(异步响应!=null)
    用户响应(异步响应);
    }
    });
    私有void消费响应(异步响应异步响应){
    开关(asyncResponse.responseStatus){
    箱子装载:{
    打破
    }
    成功案例:{
    打破
    }
    案例错误:{
    打破
    }
    违约:
    打破
    }
    
    make handleResults,handleError in methods in activity而不是viewmodelStill,如何在Activity1中同时获得结果、错误和列表。不要在
    getImages()中执行
    imageList=MutableLiveData()
    function.2.将livedata设置为val而不是var.3.在活动中也观察
    errorMessage
    ,就像通过
    getImages()观察
    imageList
    .4.当您有数据
    errorMessage.value=null
    时,不要向错误发送null。当您有错误
    imageList.value=null
    时,不要向数据发送null。请删除这些。谢谢,但您能用示例代码演示如何在活动中获取errorMessage吗