我很难理解以下代码示例的行为;
Flowable<String> f = Flowable.just(1)
.flatMap(it -> Flowable.create(e -> {
for(int i = 1; i < 1001; ++i) {
log.info("Emitting: " + i);
if(i % 10 == 0) {
Thread.sleep(1000);
}
e.onNext(i);
}
e.onComplete();
}, BackpressureStrategy.BUFFER))
.map(String::valueOf)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread());
f.subscribe(val -> {
Thread.sleep(100);
log.info("Observing: " + val);
});
Thread.sleep(1000000);
Run Code Online (Sandbox Code Playgroud)
代码运行正常,直到subscribe调用观察到 128 个项目。发射和观察是并行的。但在那之后,Flowable 继续发出项目(显然在某处排队)但直到所有 1000 个项目都发出后才观察到任何项目。在发出所有 1000 个项目后,立即观察其余项目(> 128 个)。
这看起来与 128 的背压 bufferSize 相关,但我仍然希望发射和观察对于整个 1000 个项目是并行的,因为观察者显然不比发射器慢。有什么我在这里想念的吗?我应该怎么做才能修复代码?
我正在尝试为使用 Retrofit 2、Mockito 1.10 和 RXJava 1.0 的 Android 应用程序编写一些单元测试。我没有使用支持 lambda 的 Java 版本!
我的代码使用 Observables,我可以执行以下操作:
when(myAPI.Complete(anyString(), any(MyContainer.class)))
.thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));
Subscriber genericResponseSubscriber = mock(Subscriber.class);
myPresenter.myUseCase(id, container, genericResponseSubscriber);
verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,并允许我抛出错误并在测试中捕获它。
我也需要做的(当然):) 是捕捉积极的条件。我觉得这很明显,但找不到我需要的答案。
如何捕获 onComplete 和 onNext 案例?
我知道 onComplete 的验证将是......
验证(genericResponseSubscriber, times(1)).onCompleted();
但我看不出我的“何时”条款应该是什么。我尝试了以下但失败了:
GenericResponse response = new GenericResponse();
response.setSuccess(true);
when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
.thenReturn(Observable.just(response));
Subscriber genericResponseSubscriber = mock(Subscriber.class);
myPresenter.myUseCase(id, container, genericResponseSubscriber);
verify(genericResponseSubscriber, times(1)).onCompleted();
Run Code Online (Sandbox Code Playgroud)
这里的失败是subscriber.onStart() 被调用了。
所以,我想知道的是,我如何模拟和验证“onComplete”和“onNext”调用,更重要的是我应该看起来能够自己解决这个问题而不是问!:)
与往常一样,任何帮助表示赞赏。
编辑..
我的 onError 工作测试用例..
public void UseCaseOnError() throws Exception {?
String id …Run Code Online (Sandbox Code Playgroud) 为什么这是抱怨小姐类型?map应该将一个 observable 的值转换为另一个,但它希望我从地图中返回一个 observable
override fun fetchExercises(): Observable<List<Exercise>> {
return FirebaseDatabase.getInstance()
.getReference("exercises")
.observeSingleEvent()
.map { snapshot: DataSnapshot? -> object: List<Exercise>
// Error here
return listOf<Exercise>()
}
}
fun DatabaseReference.observeSingleEvent(): Observable<DataSnapshot> {
return Observable.create(object : Observable.OnSubscribe<DataSnapshot> {
override fun call(subscriber: Subscriber<in DataSnapshot>) {
val valueEventListener = object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot?) {
subscriber.onNext(snapshot)
subscriber.onCompleted()
}
override fun onCancelled(error: DatabaseError?) {
subscriber.onError(FirebaseDatabaseThrowable(error))
}
}
addListenerForSingleValueEvent(valueEventListener)
}
})
}
Run Code Online (Sandbox Code Playgroud) 我是 RxJava 的新手。我的经验主要来自这些教程: here和here。
现在,我发现自己在使用 Retrofit2 进行 API 调用时会返回一个Obesrvable<AccessToken>. 客户端将调用此服务如下:
public Observable<TokenResult> authenticateWithClientCredentials() {
return authService.authenticate("client_credentials").take(1);
}
Run Code Online (Sandbox Code Playgroud)
Authenticator调用的类#authenticateWithClientCredentials()将从客户端调用。
我想要实现的是Observable<Boolean>从Authenticator类中返回一个,一旦 API 调用完成,即 insideonComplete()表示访问令牌已成功获取并保存在Authenticator类内的缓存中。
我试过defer接线员,但我还是迷路了。
编辑
我知道我可以在参数中传递一个回调,但是 Rx 的想法不是取代旧的经典回调方法吗?
我正在尝试执行以下操作:
A
|
|
V
Observable<B>
/\
/ \
/ \
V V
Observable<C> Observable<D>
\ /
\ /
V V
Observable<E>
Run Code Online (Sandbox Code Playgroud)
我是 RxJava 的新手,遇到过 zip、merge 等,但并不真正了解此类问题需要哪些运算符。任何帮助将不胜感激。
附注。1) 虽然 [C] 和 [D] 都是必需的,但仍然可以仅使用其中之一创建 [E]。因此,如果其中一个(或两个)失败,此时最好有一个超时。
2)是否可以让它们在特定线程中运行——一个在计算()中,另一个在 io()中?
这是我目前拥有的概念性代码。我这样做是线性的:
A -> B -> C -> D -> E
return a2b(a)
.subscribeOn(Schedulers.io())
.flatMap(this::b2c)
.subscribeOn(Schedulers.computation())
.map(this::c2d)
.map(this::d2e)
.cast(E.class)
.startWith(e -> new E.loadingState());
Run Code Online (Sandbox Code Playgroud)
理想情况下,我应该在某处使用以下函数:
Observable<E> cd2e(C c, D d) {
return Observable.just(new E());
}
Run Code Online (Sandbox Code Playgroud)
谢谢。
我直接说重点。当我尝试运行该应用程序时,我遇到了一些错误
package com.google.api.client.extensions.android.http does not exist
package com.google.api.client.extensions.android.json does not exist
package io.reactivex does not exist
Run Code Online (Sandbox Code Playgroud)
build.gradle 文件
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
compile 'com.pkmmte.view:circularimageview:1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.yalantis:ucrop:2.2.1'
compile 'com.android.support:design:23.3.0'
compile 'com.google.android.gms:play-services-gcm:11.0.4'
compile 'com.writingminds:FFmpegAndroid:0.3.2'
compile 'com.google.apis:google-api-services-youtube:v3-rev186-1.23.0'
compile group: 'com.google.oauth-client', name: 'google-oauth-client-java6', version: '1.23.0'
compile group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.23.0'
compile 'com.github.PierfrancescoSoffritti:AndroidYouTubePlayer:4.1.7'
//compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
//compile …Run Code Online (Sandbox Code Playgroud) 如果是按钮,则表达式:
yourButton.setOnclicklistener(new .....)
Run Code Online (Sandbox Code Playgroud)
可以用 RxJava 编写,如:
RxView.clicks(yourButton).subscribe(....)
Run Code Online (Sandbox Code Playgroud)
我想知道对于 Android 是否Switch可以使用以下表达式编写RxJava
常规版本:
yourSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
Run Code Online (Sandbox Code Playgroud)
拉姆达版本:
yourSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
});
Run Code Online (Sandbox Code Playgroud)
RxJava 版本???
我正在Room用作 ORM,这是我的 Dao 界面:
@Dao
interface UserDao {
@Query(value = "SELECT * FROM User LIMIT 1")
fun get(): Single<User?>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun add(profile: User)
}
Run Code Online (Sandbox Code Playgroud)
另一方面,我在 Repository 中有一个方法可以检查用户是否登录,这是实现代码:
override fun isUserLogin(): Single<Boolean> = userDao
.get().async()
.onErrorReturn { null }
.map { it != null }
Run Code Online (Sandbox Code Playgroud)
如果没有行匹配查询,Room 将抛出以下异常:
查询返回空结果集:SELECT * FROM User LIMIT 1
我想null在这种情况下返回,但是当我执行代码时,它会抛出一个异常并显示以下消息:
提供的值为空
我不能使用Optional因为 Dao 正在返回Single<User?>所以onErrorReturn应该返回相同的类型。
如何在不更改 Dao 的情况下检查用户是否存在?
我在一个方法中有 2 个可完成项,例如:
completable1.doSomething()
.andThen(completable2.doSomethingElse())
Run Code Online (Sandbox Code Playgroud)
我想通过使用 Mockito 并在第一个可完成项中返回错误来测试它。这是我的原始方法:
public Completable updateQuestion(Question question){
return gameRepositoryType.updateQuestion(question)
.andThen(gameRepositoryType.getGameById(question.getqId())
.map(GAME_MAPPER)
.flatMapCompletable(gameRepositoryType::updateGame))
.observeOn(AndroidSchedulers.mainThread());
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
@Test
public void updateQuestionError(){
when(gameRepositoryType.updateQuestion(question)).thenReturn(Completable.error(error));
when(question.getqId()).thenReturn(FAKE_QID);
when(gameRepositoryType.getGameById(FAKE_QID)).thenReturn(Single.just(game));
when(gameRepositoryType.updateGame(game)).thenReturn(Completable.complete());
interactor.updateQuestion(question)
.test()
.assertNotComplete()
.assertError(error);
verify(gameRepositoryType).updateQuestion(question); //this is called in test
verify(question,never()).getqId(); //this is called in test
verify(gameRepositoryType,never()).getGameById(FAKE_QID); //this is called in test
verify(gameRepositoryType,never()).updateGame(game); //this is NEVER called in test
}
Run Code Online (Sandbox Code Playgroud)
在测试方法结束时的验证中,我期望在第一个可完成的发出错误后,最后 3 个验证应该成功运行,即verify()永远不应调用最后 3 个验证。
但是我可以看到,即使gameRepositoryType.updateQuestion(question)发出错误,也调用了所有方法。这是为什么?
andThen()如果第一个可完成的发出错误,不应该永远不会被调用吗?
什么时候用Completable.fromAction(),什么时候用Completable.fromCallable()有没有具体的用例
从文档看来,两者都做同样的事情,很难注意到它们之间的区别。
rx-java ×10
android ×7
rx-java2 ×5
kotlin ×2
mockito ×2
android-room ×1
concurrency ×1
java ×1
rx-android ×1
unit-testing ×1