我正在尝试解决的高级问题是使用RxJava Foo将fetched FooContainer(Observable)中包含的FooBar对象列表转换为对象列表.
我的(困惑的)尝试:
fooContainerObservable
.map(container -> container.getFooList())
.flatMap(foo -> transformFooToFooBar(foo))
.collect( /* What do I do here? Is collect the correct thing? Should I be using lift? */)
.subscribe(fooBarList -> /* Display the list */);
Run Code Online (Sandbox Code Playgroud)
我的困惑(或至少有一点)是将扁平化列表移回列表的步骤.
注意:我正在尝试在Android应用中执行此操作.
我想在调用我的rx改装服务之前检查移动设备是否已连接到互联网.如果没有连接,我想返回一个包含错误的假响应.
我结束了下面的解决方案,使用defer(),但我认为它可以更好,任何提示?
private Observable<Response> checkNetwork(Observable<Response> retrofitService) {
return Observable.defer(new Func0<Observable<Response>>() {
@Override
public Observable<Response> call() {
if (!isOnline()) {
return Observable.just(Response.error(R.string.error_no_network_label)));
}
return retrofitService;
}
});
}
Run Code Online (Sandbox Code Playgroud) 在每个应用程序启动时,我都有一个Retrofit Observable,用于从服务器获取用户的用户名.我想为每个后续订阅者使用此值,但似乎每次调用subscribe()时,都会从网络中重新获取该值.由于用户名在应用程序的生命周期中不太可能发生变化,因此我不会重新创建Observable对象,只会实例化一次.
我希望它如何工作是:
创建一次Observable
获取用户名一次,将该值保存在Observable中
在订阅时,使用该保存的值,或者如果未完成提取,则等待获取它
我该怎么办呢?
我希望实现这一点,如果我调用该Obervable.subscribe(Action1)方法,它不会抛出OnErrorNotImplementedException任何地方,但如果我调用Obervable.subscribe(Action1, Action1),则在正常引发错误时调用第二个操作.我试过两种方法:
.onErrorResumeNext(Observable.empty())
Run Code Online (Sandbox Code Playgroud)
这种方式OnErrorNotImplementedException不会被抛出,但是如果我也传递了第二个动作,那么动作也不会被调用.
第二:
.lift(new Observable.Operator<T, T>() {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
if (!subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
}
@Override
public void onError(Throwable e) {
if (!subscriber.isUnsubscribed()) {
try {
subscriber.onError(e);
} catch (Throwable t) {
if (!(t instanceof OnErrorNotImplementedException)) {
throw t;
}
}
}
}
@Override
public void onNext(T t) {
if (!isUnsubscribed()) {
subscriber.onNext(t); …Run Code Online (Sandbox Code Playgroud) 我试图在标准的JUnit测试中测试这个类,但是,我正在使用Schedulers.io()挂起NullPointerException.Schedulers.io()可以被嘲笑吗?
这是一个Android应用程序,我试图使用travis-ci进行持续集成以及用于报告覆盖率的coveralls.io来完全覆盖代码.
要测试的类:
public class GetLiveStreamsList extends UseCase {
private final String filename;
private final ContentRepository contentRepository;
public GetLiveStreamsList( final String filename, final ContentRepository contentRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) {
super( threadExecutor, postExecutionThread );
this.filename = filename;
this.contentRepository = contentRepository;
}
@Override
protected Observable buildUseCaseObservable() {
Action1<List<LiveStreamInfo>> onNextAction = new Action1<List<LiveStreamInfo>>() {
@Override
public void call( List<LiveStreamInfo> liveStreamInfos ) {
try {
Thread.sleep( 5000 );
} catch( InterruptedException e ) { }
}
};
return this.contentRepository.liveStreamInfos( this.filename )
.repeat( …Run Code Online (Sandbox Code Playgroud) 我看到ReactiveX(RxJava)有一个运算符timeout,它将应用于订阅流中的每个项目.但我只想检查超时的第一个响应,而不关心以下响应的超时.如何使用RxJava的运算符优雅地实现此要求?
下面块中的Log.d(...)表达式catch(...)被执行(我可以在 Android Studio 中看到日志输出),但调试器不会在同一行设置的断点处停止。这是为什么?调试器在其他断点处停止。
Observable.create(new Observable.OnSubscribe<MobileBankIdSessionResponse.MobileBankIdSession>() {
@Override
public void call(final Subscriber<? super MobileBankIdSessionResponse.MobileBankIdSession> subscriber) {
Schedulers.newThread().createWorker().schedule(new Action0() {
@Override
public void call() {
try {
MobileBankIdSessionResponse r = User.getMobileBankIdSession(reference, nationalIdentity).toBlocking().first();
String progressCode = r.getResponse().progress.progressCode;
if (StringUtils.equals(progressCode, "COMPLETE")) {
subscriber.onNext(r.getResponse());
subscriber.onCompleted();
} else if (StringUtils.equals(progressCode, "USER_SIGN")
|| StringUtils.equals(progressCode, "OUTSTANDING_TRANSACTION")) {
Schedulers.newThread().createWorker().schedule(this, 2, TimeUnit.SECONDS);
} else if (StringUtils.equals(progressCode, "NO_CLIENT")) {
subscriber.onError(new Throwable("Fel vid signering"));
}
} catch (Exception e) {
Log.d("AtError", "here");
subscriber.onError(e);
}
}
});
} …Run Code Online (Sandbox Code Playgroud) 大家!我有一些问题.我是RxJava/RxKotlin/RxAndroid的初学者,并且不了解一些功能.例如:
import rus.pifpaf.client.data.catalog.models.Category
import rus.pifpaf.client.data.main.MainRepository
import rus.pifpaf.client.data.main.models.FrontDataModel
import rus.pifpaf.client.data.product.models.Product
import rx.Observable
import rx.Single
import rx.lang.kotlin.observable
import java.util.*
class MainInteractor {
private var repository: MainRepository = MainRepository()
fun getFrontData() {
val cats = getCategories()
val day = getDayProduct()
val top = getTopProducts()
return Observable.zip(cats, day, top, MainInteractor::convert)
}
private fun getTopProducts(): Observable<List<Product>> {
return repository.getTop()
.toObservable()
.onErrorReturn{throwable -> ArrayList() }
}
private fun getDayProduct(): Observable<Product> {
return repository.getSingleProduct()
.toObservable()
.onErrorReturn{throwable -> Product()}
}
private fun getCategories(): Observable<List<Category>> {
return repository.getCategories()
.toObservable() …Run Code Online (Sandbox Code Playgroud) 我有以下RxJava2 Kotlin代码:
val tester = Completable.complete()
.andThen(SingleSource<Int> { Single.just(42) })
.test()
tester.assertComplete()
tester.assertValue(42)
Run Code Online (Sandbox Code Playgroud)
这模拟了一个Completable observable(想象一个对API的简单更新操作),然后是一个Single observable(在API上映像获取操作).我希望以一种方式连接两个observable,当Completable完成时,Single运行,最后我在我的观察者(Int 42)上获得onSuccess事件.
但是这个测试代码不起作用.断言失败,出现以下错误:
java.lang.AssertionError: Not completed
(latch = 1, values = 0, errors = 0, completions = 0))
Run Code Online (Sandbox Code Playgroud)
我无法理解我做错了什么,我希望Completable在订阅时发出onComplete,然后Single订阅,我的observer(tester)获得一个值为42的onSuccess事件,但似乎订阅仍然"暂停" "没有发光.
这个想法类似于这篇博文中的内容:https://android.jlelse.eu/making-your-rxjava-intentions-clearer-with-single-and-completable-f064d98d53a8
apiClient.updateMyData(myUpdatedData) // a Completable
.andThen(performOtherOperation()) // a Single<OtherResult>
.subscribe(otherResult -> {
// handle otherResult
}, throwable -> {
// handle error
});
Run Code Online (Sandbox Code Playgroud) 我有一个用例,我在一个Completable中初始化一些全局变量,并在链的下一步(使用andThen运算符)我使用这些变量.
以下示例详细解释了我的用例
说你上课了 User
class User {
String name;
}
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的Observable,
private User mUser; // this is a global variable
public Observable<String> stringObservable() {
return Completable.fromAction(() -> {
mUser = new User();
mUser.name = "Name";
}).andThen(Observable.just(mUser.name));
}
Run Code Online (Sandbox Code Playgroud)
首先,我正在做一些初始化,我Completable.fromAction希望andThen操作员只有在完成后才能启动Completable.fromAction.
这意味着我希望mUser在andThen运营商启动时进行初始化.
以下是我对此观察的订阅
stringObservable()
.subscribe(s -> Log.d(TAG, "success: " + s),
throwable -> Log.e(TAG, "error: " + throwable.getMessage()));
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,我收到一个错误
Attempt to read from field 'java.lang.String User.name' on a null object reference …Run Code Online (Sandbox Code Playgroud)