当我在Android中使用ViewModel时,我在ViewModel类中使用了两个MutableLiveData对象。var imageList: MutableLiveData<List<HitsItem>> = MutableLiveData()var errorMessage: MutableLiveData<String> = MutableLiveData()我想要的是每当API调用errorMessage中发生错误时,类似地,当API调用成功时,就设置imageList。如何在Activity中检查API是否成功,当API调用不成功时,我想在Activity中显示Toast错误消息?ImageViewModel.ktfun 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} Activity lateinit var imagesViewModel:ImagesViewModellateinit var adapter:ImageAdapteroverride 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 } } })} 最佳答案 创建网络响应类:公共(public)类AsyncResponse {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);}} 创建一个枚举类:公共(public)枚举ResponseStatus { 加载,成功,错误 在您的viewmodel类中,无论何时收到响应,都只需发布值:私有(private)MutableLiveData asyncResponseMutableLiveData=新的MutableLiveData ();响应成功:asyncResponseMutableLiveData.postValue(AsyncResponse.success());响应错误:asyncResponseMutableLiveData.postValue(AsyncResponse.error(new Throwable(e))); 4.在“ Activity 类”中,观察响应 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; } 10-08 17:51