RxJava 2/改造2-NetworkOnMainThreadException [英] RxJava 2 / Retrofit 2 - NetworkOnMainThreadException

查看:73
本文介绍了RxJava 2/改造2-NetworkOnMainThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个请求,如果我的令牌已过期,我需要刷新它,然后重试该请求.

I need to perform a request, if my token is expired I need to refresh it and retry the request.

这是我正在尝试执行的操作,目前我可以刷新令牌,但它引发了NetworkOnMainThreadException.它完成了请求,更新了令牌并到达了日志,但是那异常杀死了我.我该如何避免呢?

This is how I'm trying to do it, at the moment I can refresh the token but it throws me a NetworkOnMainThreadException. It finishes the request,update the token and reaches logs, but that exception its killing me. How can I avoid that?

    public Observable<Estabelecimento> listarEstabelecimentos() {
    return Observable.defer(this::getListarEstabelecimentoObservable)
            .retryWhen(throwableObservable -> throwableObservable.flatMap(
                    throwable -> {
                        if (throwable instanceof UnauthorizedException) {
                            return mRequestManager.getTokenObservable(AutoAtendimentoApplication.getContext())
                                    .doOnNext(response -> /* log stuff */)
                                    .flatMap((Function<AuthResponse, ObservableSource<?>>) response2 ->
                                            getListarEstabelecimentoObservable()
                                                    .doOnNext(estabelecimento ->
                                                            /* log stuff */)
                                                    )
                                    );
                        }
                        return Observable.error(throwable);
                    }));
}

NetWorkErrorHandler:

NetWorkErrorHandler:

    public <T> T  processError(Response<T> response ) {
    switch (response.code()) {
        case 401:
            throw new UnauthorizedException();
        default:
            return response.body();
    }
}

令牌:

       private Observable<AuthResponse> getToken(Context context,
                                          @GrantType.GrantTypeDef String grantType, @Nullable String refreshToken) {

    SessionManager sessionManager = SessionManager.getInstance(context);
    Usuario usuario = sessionManager.getUser();

    AuthRequest request = new AuthRequest(usuario.getUsername(),
            usuario.getPassword(), grantType, refreshToken);

    return mAuthAPIService.getToken(request)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .map(response -> storeTokens(response, context));
}

我很确定问题发生在平面图内,并且subscribeOn不能解决问题

Edit 1: I'm pretty sure the problem happens inside the flatmap and put subscribeOn does not solve the problem

代码更新

推荐答案

您的网络正在主线程上运行,您可以通过添加 observeOn(AndroidSchedulers.mainThread())您可以观察到的subscribeOn(Schedulers.io()).

Your network is running on main thread, you can solve it by adding observeOn(AndroidSchedulers.mainThread()) and subscribeOn(Schedulers.io()) to your observable.

observeOn(...)意味着结果将在指定的线程(在本例中为UI线程)上发出.

The observeOn(...) means that the results are emmited on the specified thread - in this case the UI thread.

subscribeOn(...)调用基本上是处理请求的位置.如果省略,则计算在当前线程上完成.

The subscribeOn(...) call is basically where the request is processed. If omitted the computation is done on current thread.

这篇关于RxJava 2/改造2-NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆