我有Repository方法:
public Maybe<String> getId(String id){
return mApiInterface.get().getId(id)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.mainThread());
}
我试图在延迟循环中使用此方法:
final ArrayList<String> ids = SharedPreferenceProvider.getIds();
for(final String id:ids) {
mRepository.get().getId(id)
.delay(5, TimeUnit.SECONDS)
.subscribeWith(new DisposableMaybeObserver<String>() {
@Override
public void onSuccess(String s) { }
@Override
public void onError(Throwable e) { }
@Override
public void onComplete() { }
});
}
但是延迟方法不起作用。我究竟做错了什么?有时我需要在两个请求之间延迟。
决定的最终变体:
Flowable.zip(Flowable.fromIterable(ids),
Flowable.interval(0, 5, TimeUnit.SECONDS).onBackpressureBuffer(),
new BiFunction<String, Long, String>() {
@Override
public String apply(String s, Long aLong) throws Exception {
return s;
}
}
).flatMapMaybe(new Function<String, MaybeSource<String>>() {
@Override
public MaybeSource<String> apply(String s) throws Exception {
return mRepository.get().testMaybe(s);
}
}).subscribeWith(new DisposableSubscriber<String>() {
@Override
public void onNext(String s) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
});
答案 0 :(得分:3)
我需要每隔5秒发送一次带id的请求。
但我需要 - mRepository.get()。getId(id1) - 等待5秒 - mRepository.get()。getId(id2) - 等待5秒 - 等等
您可以使用间隔进行压缩,然后在存储库调用中使用flatMap
Flowable.fromArray(ids) // or fromIterable(ids)
.zipWith(
Flowable.interval(0, 5, TimeUnit.SECONDS).onBackpressureBuffer(),
(id, time) -> id
)
.flatMapMaybe(id -> mRepository.get().getId(id), 1)
// .repeat()
.subscribe(/* ... */)
答案 1 :(得分:0)
试试吧!
public Maybe<String> getId(String id){
return mApiInterface.get().getId(id)
.delay(5, TimeUnit.SECONDS)
.subscribeOn(mSchedulerProvider.io());
}
//和
for(final String id:ids) {
mRepository.get().getId(id)
.observeOn(mSchedulerProvider.mainThread())
.subscribeWith(new DisposableMaybeObserver<String>()
{
@Override
public void onSuccess(String s) { }
@Override
public void onError(Throwable e) { }
@Override
public void onComplete() { }
});
}