TonnyL / Espresso

🚚 Espresso is an express delivery tracking app designed with Material Design style, built on MVP(Model-View-Presenter) architecture with RxJava2, Retrofit2, Realm database and ZXing
Apache License 2.0
1.09k stars 200 forks source link

请教个问题 #11

Closed PiPiCaptain closed 7 years ago

PiPiCaptain commented 7 years ago

'compositeDisposable.clear();' 这句代码只是取消RxJava订阅,还是说能真正地取消网络请求?

'compositeDisposable.clear();' Does this line clear the RxJava subscriptions or cancel the network request truly?

TonnyL commented 7 years ago

@PiPiCaptain 你好 应该是取消订阅。

Hi, The answer should be cancelling all the subscriptions.

PiPiCaptain commented 7 years ago

@TonnyL 如果想真正地取消网络请求,应该怎么做?有没有研究?

wbinarytree commented 7 years ago

@PiPiCaptain 如果是使用的Retrofit官方Adapter。 那么dispose会自动取消网络请求。如果是自己封装的网络请求。使用

Observable.create(e -> e.setCancellable(() ->  request.cancel()));

来自动取消请求。

PiPiCaptain commented 7 years ago

@wbinarytree 我现在的项目,还是在用RxJava1.x版本。因为项目里有一个第三方类库在用RxJava1.x,所以我还暂时不能转用RxJava2.x版本。我现在是用Subscription.unsubscribe();这个方法来取消,但经过网络抓包测试,只是取消了订阅,并不能取消网络请求。

PiPiCaptain commented 7 years ago

@wbinarytree 但是我看Retrofit Issues,JakeWharton大神说这个方法是可以的,但我测试了第多次,就是无法取消网络请求。 https://github.com/square/retrofit/issues/1087

wbinarytree commented 7 years ago

@PiPiCaptain 无法取消网络请求不一定是你的Subscription出了问题。 在订阅之前有没有用publish/share/replay等等操作符?

PiPiCaptain commented 7 years ago

@wbinarytree 都没用到

wbinarytree commented 7 years ago

@PiPiCaptain 代码贴出来看一下吧。

PiPiCaptain commented 7 years ago

第一步: @GET("adat/sk/{cityId}.html") Observable loadDataByRetrofitRxjava(@Path("cityId") String cityId);

第二步: addSubscription(apiStores.loadDataByRetrofitRxjava(cityId), new ApiCallback() { @Override public void onSuccess(MainModel model) { mvpView.getDataSuccess(model); }

                @Override
                public void onFailure(String msg) {
                    mvpView.getDataFail(msg);
                }

                @Override
                public void onFinish() {
                    mvpView.hideLoading();
                }

            });

public abstract class BasePresenter implements Presenter { public V mvpView; private CompositeSubscription mCompositeSubscription;

@Override
public void attachView(V mvpView) {
    this.mvpView = mvpView;
    initApiStores();
}

@Override
public void detachView() {
    this.mvpView = null;
    unsubscribe();
}

//RXjava取消注册,以避免内存泄露
private void unsubscribe() {
    if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
        mCompositeSubscription.unsubscribe();
    }
}

public void addSubscription(Observable observable, Subscriber subscriber) {
    if (mCompositeSubscription == null) {
        mCompositeSubscription = new CompositeSubscription();
    }
    mCompositeSubscription.add(observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread(),true)
            .unsubscribeOn(Schedulers.io())
            .subscribe(subscriber));
}

protected abstract void initApiStores();

}

public abstract class ApiCallback extends Subscriber {

public abstract void onSuccess(M model);

public abstract void onFailure(String msg);

public abstract void onFinish();

@Override
public void onError(Throwable e) {
    e.printStackTrace();
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        //httpException.response().errorBody().string()
        int code = httpException.code();
        String msg = httpException.getMessage();
        LogUtil.d("code=" + code);
        if (code == 504) {
            msg = "网络不给力";
        }
        if (code == 502 || code == 404) {
            msg = "服务器异常,请稍后再试";
        }
        onFailure(msg);
    } else {
        onFailure(e.getMessage());
    }
    onFinish();
}

@Override
public void onNext(M model) {
    onSuccess(model);

}

@Override
public void onCompleted() {
    onFinish();
}

}

public class AppClient { public static Retrofit mRetrofit;

public static Retrofit retrofit() {
    if (mRetrofit == null) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiStores.API_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }
    return mRetrofit;
}

}

PiPiCaptain commented 7 years ago

@wbinarytree 上面的代码

wbinarytree commented 7 years ago

@PiPiCaptain 。看起来没什么大问题 CompositeSubscription用clear()代替unsubscribe()试一下?

TonnyL commented 7 years ago

Then I will close this issue, if you have any other problem about it, do not hesitate to reopen it or just open another one. Happy coding😀!