在我的项目中,我需要处理不同线程中的对象.为了操纵流的行为,我创建了新的observable来改变它们的observeOn()方式:
apiService.getObjects(token) // Retrofit
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(o -> {
// process in Main Thread
})
.map(Observable::just) // create new one, to change thread for it
.observeOn(Schedulers.io())
.subscribe(o -> {
// process in the background thread
});
Run Code Online (Sandbox Code Playgroud)
但我认为在RxJava中有更多美观有效的方法来处理不同线程中的一个响应.我试着谷歌,但我没有找到任何东西.
谢谢,
安东
我有以下方法使用Retrofit服务接口从API获取一些数据,然后与view接口交互.
@Override
@VisibleForTesting
public void fetchPhotos(@Nullable PhotosService service, @Nullable Scheduler subscribeOn) {
view.showLoading();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.PLACEHOLDER_API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
if (service == null) service = retrofit.create(PhotosService.class);
if (subscribeOn == null) subscribeOn = Schedulers.newThread();
service.listPhotos()
.subscribeOn(subscribeOn)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(photoList -> {
Log.d(TAG, "got photos " + photoList.toString());
view.unshowLoading();
}, throwable -> {
Log.d(TAG, "error " + throwable.toString());
view.unshowLoading();
view.displayError(throwable.toString(), v -> fetchPhotos());
});
}
Run Code Online (Sandbox Code Playgroud)
我想测试view.unshowLoading()onNext中调用的那个.
这是我的测试:
@Test
public void viewUnshowsLoadingAfterFetchingPhotos() {
PhotosListView view …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用retrofit + rxjava来进行嵌套的api调用.基本上我必须构建一个Library对象列表.每个Library对象都有一个Authors列表,每个Author对象都有一个Books列表.这就是我的json的结构.
图书馆json -
{
title: "Library",
items: [
{
title: "Library1"
image: "http://example.com/image/101/image_lib1.png"
url: "http://example.com/api/1"
},
{
title:"Library2"
image: "http://example.com/image/101/image_lib2.png"
url: "http://example.com/api/2"
},
{
title:"Library3"
image: "http://example.com/image/101/image_lib3.png"
url: "http://example.com/api/3"
}
]
}
Run Code Online (Sandbox Code Playgroud)
和作者json-
{
title: "Authors",
items: [
{
title: "J.K Rowling"
image: "http://example.com/image/101/image_author1.png"
url: "http://example.com/api/101"
},
{
title:"Mark Twain"
image: "http://example.com/image/101/image_author2.png"
url: "http://example.com/api/201"
},
{
title:"Charles Dickens"
image: "http://example.com/image/101/image_author3.png"
url: "http://example.com/api/301"
}
]
}
Run Code Online (Sandbox Code Playgroud)
和书籍json-
{
description: Books,
imageurl: "http://example.com/image/101/image_101.png",
items: [
{
id: 101,
title: "Oliver …Run Code Online (Sandbox Code Playgroud) 问题是关于rx编程.我有一个代码:
Observable.from(array)
.map(array_item1 -> array_item2)
.map(array_item3 -> array_item4)
.map(array_item5 -> array_item6)
Run Code Online (Sandbox Code Playgroud)
而在第三个map电话,我需要访问不仅array_item5也array_item1还是array_item3.看起来应该是这样的:
...
.map(array_item5 -> array_item5 + array_item1)
...
Run Code Online (Sandbox Code Playgroud)
这有什么特殊的模式或操作符吗?
我实现了两个存储库以管理我的数据.因此,如果数据库中没有数据,则应向API询问相关信息.我在其他帖子中看到这可以使用switchIfEmpty解决,但它对我不起作用.
我尝试了以下代码.调用行restApiFlavorRepository.query(规范),但永远不会通知订阅者.
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.map(new Func1() {
@Override
public Observable<List<Flavor>> call(Object o) {
if(((ArrayList<Flavor>)o).isEmpty()) {
return restApiFlavorRepository.query(specification);
}
return null;
}
});
}
Run Code Online (Sandbox Code Playgroud)
还有这个
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.switchIfEmpty(restApiFlavorRepository.query(specification));
}
Run Code Online (Sandbox Code Playgroud)
当我获得两种口味时,我仍然会得到空列表.
更新
我在找什么,是这个......
public Observable query(Specification specification) {
Observable<List<Plant>> query = mRepositories.get(0).query(specification);
List<Plant> list = new ArrayList<>();
query.subscribe(plants -> list.addAll(plants));
Observable<List<Plant>> observable = Observable.just(list);
return observable.map(v -> !v.isEmpty()).firstOrDefault(false)
.flatMap(exists -> …Run Code Online (Sandbox Code Playgroud) 这里的逻辑是,如果数据库中的等级为空,那么我想从API中获得它们。我有以下代码:
Observable.from(settingsRatingRepository.getRatingsFromDB())
.toList()
.switchIfEmpty(settingsRatingRepository.getSettingsRatingModulesFromAPI())
.compose(schedulerProvider.getSchedulers())
.subscribe(ratingsList -> {
view.loadRatingLevels(ratingsList, hideLocks);
}, this::handleError);
Run Code Online (Sandbox Code Playgroud)
该getRatingsFromDB()调用返回List<SettingRating>,但是API调用返回Observable<List<SettingRating>>。
但是,当我对此进行单元测试时,当我从数据库调用传递空列表时,它不执行API调用。有人可以帮我解决这个问题。这是我的单元测试代码:
when(mockSettingsRatingsRepository.getRatingsFromDB()).thenReturn(Collections.emptyList());
List<SettingsRating> settingsRatings = MockContentHelper.letRepositoryReturnSettingsRatingsFromApi(mockSettingsRatingsRepository);
settingsParentalPresenter.onViewLoad(false);
verify(mockView).loadRatingLevels(settingsRatings, false);
Run Code Online (Sandbox Code Playgroud) 我是新手,RxJava只是尝试实现一些例子来更好地理解发生了什么,所以我想到的EditText是一个Observable并textChangeEvent使用RxBinding库发出:
RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS)
.filter(new Func1<TextViewTextChangeEvent, Boolean>() {
@Override
public Boolean call(TextViewTextChangeEvent text) {
return (text.text().length() > 2);
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io());
Run Code Online (Sandbox Code Playgroud)
和Retrofitapi调用,其中呼叫的文本来自Observable上面.
所以我宣布了一个功能:
@Override
public Observable<SearchResponse> executeSearch(Observable<RxTextView> queryText) {
return searchService.getSearch(queryText)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
Run Code Online (Sandbox Code Playgroud)
现在我必须将这两者结合起来,所以当文本发生变化时,会有一个新的Retrofit呼叫,但我不知道如何"传递" queryText到服务.
我也尝试过:
Observable<TextViewTextChangeEvent>
searchBarText = RxTextView.textChangeEvents(searchbar.getEditText())
.debounce(400, TimeUnit.MILLISECONDS)
.filter(new Func1<TextViewTextChangeEvent, Boolean>() {
@Override
public Boolean call(TextViewTextChangeEvent text) {
Timber.i("Executes!!! text : %s", text.text().toString());
return (text.text().length() > 2);
}
}) …Run Code Online (Sandbox Code Playgroud) 我有一个RxJava链请求,该请求应该释放一些锁onError()或onComplete(),所以,基本上,我的问题是:当我对OkHttpClient设置读取,连接和写入超时时,我没有得到想要的行为。我正在使用Retrofit2和OkHttp3.6.0,这是我的简化客户端:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
OkHttpClient okHttpClient = builder.build();
Run Code Online (Sandbox Code Playgroud)
这是我拥有的连锁请求的简化版本:
public <T extends Response> Observable<T> doSomething(Observable<T> base) {
isLocked = true;
return someApiCall()
.flatMap(apiResponse -> handleResponse(apiResponse, base)
.doOnError(throwable -> {
isLocked = false;
})
.doOnCompleted(() -> {
isLocked = false;
}));
}
Run Code Online (Sandbox Code Playgroud)
handleResponse()进行另一个API调用并返回,Observable<Response<Something>>但是,正如我已经说过的,它有时会以失败,HTTP FAILED: java.net.SocketException: Socket closed并且永远不会完成Observable,因此,永远不会调用onError()或onComplete()。我也尝试过onTerminate(),但是没有运气。当我从中删除超时设置时OkHttlClient,SocketException实际上会引发并捕获,从而释放isLocked变量。我试过handleResponse()用一个try {} catch (Exception e) {}块包装return语句,但是即使SocketException在设置自定义超时时也无法捕获。有任何想法吗?
我有一个EditText视图和TextWatcher,在onTextChanged方法我必须从EditText字段查询服务器的结果.在我的演示者中,我使用rx,但我需要延迟搜索,直到用户的输入结束.这时我得到了这个:
service.getData(query)
.delaySubscription(REQUEST_DELAY_FROM_SERVER, TimeUnit.MILLISECONDS, Schedulers.io())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
data-> {
getViewState().showData(data);
},
error -> {
Log.e(this.getClass().getSimpleName(), error.getMessage(), error);
}
);
Run Code Online (Sandbox Code Playgroud)
但是delaySubscription不能按预期工作.它收集所有呼叫,延迟后发送每个呼叫.我必须做同样的事情,好像我曾经使用过handler.postDelayed(),只发送一次请求.
我正在使用RxAndroid 2.0.1和RxJava 2.0.6。
我有两个观察值:一个Maybe<MyObject>基于某些字符串(ID)的返回。当返回可选对象时,我必须调用第二个对象,该对象采用MyObject实例,并Single<Boolean>在对象满足某些条件时返回。然后,我可以对对象实例进行进一步的操作。
我当前的实现如下:
objectDAO.getById(objectId)
.subscribe(
myObject -> checkCondition(myObject),
throwable -> /* Fallback */,
() -> /* Fallback */
);
private void checkCondition(final MyObject myObject) {
otherDAO.checkCondition(myObject)
.subscribe(
isTrue -> {
if (isTrue) {
// yay! now I can do what I need with myObject instance
} else {
/* Fallback */
}
},
throwable -> /* Fallback */
);
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道如何简化我的代码。我的想法:
尝试使用zip-我不能这样做,因为直到第一个Observable返回MyObject之前,第二个Observable才能被订阅
尝试使用filter-现在的问题是,我需要使用阻塞获取来调用第二个可观察的对象。它可以正常工作,但看起来像代码气味:
objectDAO.getById(objectId)
.filter(myObject ->
otherDAO.checkCondition(myObject).blockingGet()
)
.subscribe(
myObject …Run Code Online (Sandbox Code Playgroud)