gpt4 book ai didi

android - NetworkOnMainThreadException 与 .subscribeOn(Schedulers.newThread())

转载 作者:行者123 更新时间:2023-11-29 18:57:12 28 4
gpt4 key购买 nike

我正在尝试使用 Retrofit 和 RxJava 从 api 获取列表并显示在 recyclerview 中。

我使用了下面的代码-

    ApiInterface apiService =
ApiService.getClient().create(ApiInterface.class);

Observable<MoviesResponse> call = apiService.getTopRatedMovies(API_KEY);
call.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
call.subscribe(new Observer<MoviesResponse>() {
@Override
public void onSubscribe(Disposable d) {
Toast.makeText(getApplicationContext(), d.toString(), Toast.LENGTH_LONG).show();

}

@Override
public void onNext(MoviesResponse moviesResponse) {
movies=moviesResponse;
moviesAdapter.notifyDataSetChanged();
}

@Override
public void onError(Throwable e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

}

@Override
public void onComplete() {
Toast.makeText(getApplicationContext(), "complete", Toast.LENGTH_LONG).show();

}
});

下面两行指定将在新线程中进行 REST 调用。当调用响应返回时,在 mainThread 上调用 onNext、onError 和 onComplete 方法。

.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())

但我收到 NetworkOnMainThreadException,当应用程序试图在其主线程上执行网络操作时会抛出该异常。为什么会收到此异常,我该如何解决?

最佳答案

那是因为您订阅了 2 次 observable。您可以从这里删除订阅方法:

call.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();

所以它看起来像这样:

ApiInterface apiService =
ApiService.getClient().create(ApiInterface.class);

call.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<MoviesResponse>() {
@Override
public void onSubscribe(Disposable d) {
Toast.makeText(getApplicationContext(), d.toString(), Toast.LENGTH_LONG).show();

}

@Override
public void onNext(MoviesResponse moviesResponse) {
movies=moviesResponse;
moviesAdapter.notifyDataSetChanged();
}

@Override
public void onError(Throwable e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

}

@Override
public void onComplete() {
Toast.makeText(getApplicationContext(), "complete", Toast.LENGTH_LONG).show();

}
});

关于android - NetworkOnMainThreadException 与 .subscribeOn(Schedulers.newThread()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com