使用MVP模式时如何取消模型中的改装请求

时间:2019-05-23 08:08:03

标签: android retrofit mvp

enter image description here我想在Android中使用MVP模式取消模型实现中的请求 我使用Retrofit2。在这种方法中,我发送了文件路径和状态进行检查,因为按钮操作使(上载,取消)功能相同。

this snipet of class

{公共类ModelImpl实现了UploadInterface.Interactor,ProgressRequestBody.UploadCallbacks {enter image description here     //我们可以在此处使用改造调用的另一种方式来上传文件并     //返回模型接口内部的OnFinishedListener接口的结果     //我们使用此处服务上传以在后台服务中运行     //这样,我们可以取消请求并重试     //但是在服务中使用意图服务很难停止,因为它旨在     //运行长任务并与调用者自行停止。

private OnProgressListener listener;

public ModelImpl(OnProgressListener listener) {
    this.listener = listener;
}

@Override
public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
    // call servce to start upload throw service

    /*Intent mIntent = new Intent(context, FileUploadService.class);
    mIntent.putExtra("mFilePath", filePath);
    FileUploadService.enqueueWork(context, mIntent);*/

    // starting http service upload

    if (!filePath.isEmpty()) {

        File file = new File(filePath.trim());
        ProgressRequestBody fileBody = new ProgressRequestBody(file, "image", this);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

        RestApiService apiService = RetrofitInstance.getApiService();

        Call<PojoResponse> callUpload = apiService.onFileUpload2(filePart);
        if (status.equals("upload")) {
            callUpload.enqueue(new Callback<PojoResponse>() {

                @Override
                public void onResponse(Call<PojoResponse> call, Response<PojoResponse> response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());

                }

                @Override
                public void onFailure(Call<PojoResponse> call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }

                    //onFinishedListener.onFailure(call, t);


                }
            });
        } else {
            if (callUpload != null && callUpload.isExecuted()) {
              callUpload.cancel();
            }

        }
    }


}

}

1 个答案:

答案 0 :(得分:0)

    package com.example.mvp2.ui.main.model;

import android.util.Log;

import com.example.mvp2.ui.main.network.RestApiService;
import com.example.mvp2.ui.main.network.RetrofitInstance;
import com.example.mvp2.ui.main.utils.ProgressRequestBody;
import com.example.mvp2.ui.main.views.upload.UploadInterface;

import java.io.File;

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModelImpl implements UploadInterface.Interactor, ProgressRequestBody.UploadCallbacks {
    //another way we can use retrofit call here to upload file and
    //return result in OnFinishedListener interface inside model interface
    //we use here service to upload to run in background service
    // this way we can cancel request and retry
    //but using intent service in service difficult to stop because it designed to
    //run long task and stop it self with caller.


    private OnProgressListener listener;
    private Call < PojoResponse > callUpload;

    public ModelImpl(OnProgressListener listener) {
        this.listener = listener;
    }

    @Override
    public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
        if (!filePath.isEmpty()) {

            File file = new File(filePath.trim());
            ProgressRequestBody fileBody = new ProgressRequestBody(file,
                "image", this);
            MultipartBody.Part filePart =
                MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

            RestApiService apiService = RetrofitInstance.getApiService();

            callUpload = apiService.onFileUpload2(filePart);
            //     if (status.equals("upload")) {
            callUpload.enqueue(new Callback < PojoResponse > () {
                @Override
                public void onResponse(Call < PojoResponse > call, Response < PojoResponse > response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());
                }
                @Override
                public void onFailure(Call < PojoResponse > call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }
                }
            });
            // } 
            /* else {
                if (callUpload != null && callUpload.isExecuted()) {
                    callUpload.cancel();
                    // this will go to presenter
                    onFinishedListener.onCancel();
                }

            }*/
        }


    }

    public void cancelUpload() {
        if (callUpload != null && callUpload.isExecuted()) {
            callUpload.cancel();
            // this will go to presenter
            onFinishedListener.onCancel();
        }
    }

    @Override
    public void onProgressUpdate(int percentage) {
        Log.d("percent", "" + percentage);
        listener.onProgressChange(percentage);

    }

    @Override
    public void onError() {

    }


    @Override
    public void onFinish() {
        Log.d("percent", "" + "finishedddddd");
        listener.onProgressFinished();


    }


}

UploadActivityPresenter .java

   package com.example.mvp2.ui.main.views.upload;

import android.util.Log;

import com.example.mvp2.ui.main.model.ModelImpl;
import com.example.mvp2.ui.main.model.PojoResponse;

import retrofit2.Call;

public class UploadActivityPresenter implements UploadInterface.Presenter, UploadInterface.Interactor.OnFinishedListener, UploadInterface.Interactor.OnProgressListener {
    private UploadInterface.View view;
    private UploadInterface.Interactor model;


    public UploadActivityPresenter(UploadInterface.View view) {
        this.view = view;
  model = new ModelImpl(this);
    }


    @Override
    public void uploadBtnClicked(String status, String filePath) {
        // this interface call method upload without know about logic about it
        // model = new ModelImpl(this);
        if (view != null) {
            if (filePath.length() > 0) {
                Log.d("filepath", "" + filePath.trim());
                view.setStatus(status);
                if (model != null) {
                    if (status.equals("upload")) {
                        model.uploadImage(status, filePath, this);
                    } else {
                        model.cancelUpload()
                    }
                }
                Log.d("ss", "ssssss");
            } else {
                view.selectFileFirst();
            }


        }

    }

    @Override
    public void imageClicked() {
        if (view != null) {
            view.showFullImageInFragment();
        }
    }


    @Override
    public void onFinished(PojoResponse obj) {
        if (view != null) {
            view.getResponse(obj);
            view.setStatus("Done");
        }

    }

    @Override
    public void onFailure(Call < PojoResponse > call, Throwable t) {
        if (view != null) {
            view.errorUploading(call, t);
        }
    }

    @Override
    public void onCancel() {
        if (view != null) {

        }
    }


    @Override
    public void onProgressChange(int percent) {
        Log.d("aaaaa", "" + percent);
        if (view != null) {
            view.setProgressPercent(percent);
        }
    }

    @Override
    public void onProgressFinished() {
        if (view != null) {
            view.setProgressFinished();
        }
    }


}

这应该工作,每次您在演示者中上载图像或取消上载图像时,您都要创建一个新的Model对象,类似于在每次调用时实例化modelImpl调用对象。

确保您的演示者类仅被实例化一次。