我必须定期轮询一些RESTful端点以刷新我的Android应用程序的数据。我还必须根据连接暂停和恢复它(如果手机处于离线状态,则无需尝试)。我目前的解决方案是有效的,但它使用标准的Java ScheduledExecutorService
来执行定期任务,但我想留在Rx范例中。
这是我当前的代码,为简洁起见,跳过部分代码。
userProfileObservable = Observable.create(new Observable.OnSubscribe<UserProfile>() {
@Override
public void call(final Subscriber<? super UserProfile> subscriber) {
final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
final Runnable runnable = new Runnable() {
@Override
public void run() {
// making http request here
}
};
final List<ScheduledFuture<?>> futures = new ArrayList<ScheduledFuture<?>>(1);
networkStatusObservable.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean networkAvailable) {
if (!networkAvailable) {
pause();
} else {
pause();
futures.add(scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, SECOND_IN_MILLIS * SECONDS_TO_EXPIRE, TimeUnit.MILLISECONDS));
}
}
private void pause() {
for (ScheduledFuture<?> future : futures) {
future.cancel(true);
}
futures.clear();
}
});
final Subscription subscription = new Subscription() {
private boolean isUnsubscribed = false;
@Override
public void unsubscribe() {
scheduledExecutorService.shutdownNow();
isUnsubscribed = true;
}
@Override
public boolean isUnsubscribed() {
return isUnsubscribed;
}
};
subscriber.add(subscription);
}
}).multicast(BehaviorSubject.create()).refCount();
networkStatusObservable
基本上是一个包含在Observable<Boolean>
中的广播接收器,表示手机已连接到网络。
正如我所说,这个解决方案正在运行,但我想使用Rx方法进行定期轮询并发出新的UserProfile
,因为手动调度事件存在很多问题,我想避免这些问题。我知道Observable.timer
和Observable.interval
,但无法弄清楚如何将它们应用于此任务(我不确定是否需要使用它们)。
答案 0 :(得分:26)
在这个GitHub问题上有一些方法可能会对您有所帮助。
https://github.com/ReactiveX/RxJava/issues/448
这三个实现是:
Observable.interval(delay, TimeUnit.SECONDS).timeInterval()
.flatMap(new Func1<Long, Observable<Notification<AppState>>>() {
public Observable<Notification<AppState>> call(Long seconds) {
return lyftApi.updateAppState(params).materialize(); } });
Scheduler.schedulePeriodically
Observable.create({ observer ->
Schedulers.newThread().schedulePeriodically({
observer.onNext("application-state-from-network");
}, 0, 1000, TimeUnit.MILLISECONDS);
}).take(10).subscribe({ v -> println(v) });
Observable.create(new OnSubscribeFunc<String>() {
@Override
public Subscription onSubscribe(final Observer<? super String> o) {
return Schedulers.newThread().schedule(0L, new Func2<Scheduler, Long, Subscription>() {
@Override
public Subscription call(Scheduler inner, Long t2) {
o.onNext("data-from-polling");
return inner.schedule(t2, this, 1000, TimeUnit.MILLISECONDS);
}
});
}
}).toBlockingObservable().forEach(new Action1<String>() {
@Override
public void call(String v) {
System.out.println("output: " + v);
}
});
结论是手动递归是要走的路,因为它等到操作完成后再安排下一次执行。
答案 1 :(得分:4)
其中一个选项是使用Observable.interval并在发出间隔时检查用户状态:
Observable<Long> interval = Observable.interval(1, TimeUnit.SECONDS);
//pulling the user data
Observable<Observable<String>> userObservable = interval.map(new Func1<Long, Observable<String>>() {
Random random = new Random();
@Override
public Observable<String> call(Long tick) {
//here you are pulling user data; you should do it asynchronously - rx way - because the interval is using Schedulers.computation which is not best suited for doing io operations
switch(random.nextInt(10)){
case 0://suppose this is for cases when network in not available or exception happens
return Observable.<String>just(null);
case 1:
case 2:
return Observable.just("Alice");
default:
return Observable.just("Bob");
}
}
});
Observable<String> flatUsers = userObservable.flatMap(new Func1<Observable<String>, Observable<? extends String>>() {
@Override
public Observable<? extends String> call(Observable<String> stringObservable) {
return stringObservable;
}
});
//filter valid data
Observable<String> usersWithoutErrors = flatUsers.filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String s) {
return s != null;
}
});
//publish only changes
Observable<String> uniqueUsers = usersWithoutErrors.distinctUntilChanged();
如果您的networkStatusObservable发送至少与检查用户数据一样频繁的事件,您可以更简单地执行此操作
networkStatusObservable.sample(1,TimeUnit.Seconds).filter(/*the best is to filter only connected state */).map(/*now start pulling the user data*/)
最后,您可以创建使用调度程序定期发出用户状态的observable - 请参阅Schedulers documentation以了解哪种调度程序最适合您:
public abstract class ScheduledOnSubscribe<T> implements Observable.OnSubscribe<T>{
private final Scheduler scheduler;
private final long initialDelay;
private final long period;
private final TimeUnit unit;
public ScheduledOnSubscribe(Scheduler scheduler, long initialDelay, long period, TimeUnit unit) {
this.scheduler = scheduler;
this.initialDelay = initialDelay;
this.period = period;
this.unit = unit;
}
abstract T next() throws Exception;
@Override
public void call(final Subscriber<? super T> subscriber) {
final Scheduler.Worker worker = scheduler.createWorker();
subscriber.add(worker);
worker.schedulePeriodically(new Action0() {
@Override
public void call() {
try {
subscriber.onNext(next());
} catch (Throwable e) {
try {
subscriber.onError(e);
} finally {
worker.unsubscribe();
}
}
}
}, initialDelay, period, unit);
}
}
//And here is the sample usage
Observable<String> usersObservable = Observable.create(new ScheduledOnSubscribe(Schedulers.io(), 1, 1, TimeUnit.SECONDS ){
Random random = new Random();
@Override
String next() throws Exception {
//if you use Schedulers.io, you can call the remote service synchronously
switch(random.nextInt(10)){
case 0:
return null;
case 1:
case 2:
return "Alice";
default:
return "Bob";
}
}
});
答案 2 :(得分:3)
使用interval()有一种更简单的方法。我测试了这段代码,但它确实有效。 但首先,您应该封装要在Action1的子类中定期执行的作业。
class Act<T> implements Action1<T> {
public Service service;
public String data;
public void call(T t){
service.log(data); //the periodic job
}
}
(为了简洁起见,我公开了这些字段,但这并不可取)。现在您可以通过以下方式安排它:
Act<Long> act=new Act<>();
act.data="dummy data";
act.service=this;
Observable.interval(0l, period, TimeUnit.SECONDS).subscribeOn(Schedulers.from(Executors.newFixedThreadPool(10))).subscribe((Action1<Long>)act);
这不会阻止你的线程,不像其他答案给出的方法。这种方法允许我们将变量作为Action中的一种可变存储传递,这在后续调用中很方便。此外,这样您就可以在自己的线程池上订阅您的调用。
答案 3 :(得分:3)
简短回答。 RxJava2:
Observable.interval(initialDelay, unitAmount, timeUnit)
.subscribe(value -> {
// code for periodic execution
});
根据您的需要选择initialDelay,unitAmount和TimeUnit。
示例:0,1,TimeUnit.MINUTES。
答案 4 :(得分:1)
好的,我会发布自己的解决方案,也许有人会从中受益。我只会发布与问题相关的部分,省略HTTP和缓存内容。以下是我的表现方式:
private ConnectableObservable<Long> createNetworkBoundHeartbeatObservable(final Observable<Boolean> networkStatusObservable,
final Observable<Boolean> pauseResumeObservable) {
final Observable<Boolean> pausableHeartbeatObservable = Observable.combineLatest(networkStatusObservable, pauseResumeObservable,
new Func2<Boolean, Boolean, Boolean>() {
@Override
public Boolean call(Boolean networkAvailable, Boolean mustPause) {
return mustPause && networkAvailable;
}
}
).distinctUntilChanged();
final Observable<Boolean> hasToResumeObservable = pausableHeartbeatObservable.filter(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean networkAvailable) {
return networkAvailable;
}
});
final Observable<Boolean> hasToStopObservable = pausableHeartbeatObservable.filter(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean networkAvailable) {
return !networkAvailable;
}
});
return pausableHeartbeatObservable.concatMap(new Func1<Boolean, Observable<Long>>() {
@Override
public Observable<Long> call(Boolean shouldResumeRequests) {
if (shouldResumeRequests) {
long timeToUpdate;
final Date oldestModifiedExpiresAt = cache.oldestModifiedExpiresAt();
timeToUpdate = Math.max(0, oldestModifiedExpiresAt.getTime() - System.currentTimeMillis());
Log.d(TAG, String.format("Have to restart updates, %d seconds till next update", timeToUpdate / SECOND_IN_MILLIS));
return Observable
.timer(timeToUpdate, SECONDS_TO_EXPIRE * SECOND_IN_MILLIS, TimeUnit.MILLISECONDS)
.takeUntil(hasToStopObservable);
} else {
Log.d(TAG, "Have to pause updates");
return Observable.<Long>never().takeUntil(hasToResumeObservable);
}
}
}).multicast(PublishSubject.<Long>create());
}
正如您所看到的,暂停或恢复更新的条件变得有点复杂,添加了一个新的Observable以支持在应用程序转到后台时暂停。
然后解决方案的核心是concatMap
操作,它按顺序发出Observables
(因此concatMap,而不是flatMap,请参阅此问题:What is the difference between concatMap and flatMap in RxJava)。它会发出interval
或never
Observables
,具体取决于是应该继续更新还是暂停更新。然后,每个发出的Observable
takenUntil
都是Observable
&#39; ConnectableObservable
会发出新的价值。
Observable
是因为创建的connect
很热,并且所有预期订阅者在开始发送内容之前都必须订阅它,否则初始事件可能会丢失。我稍后会打电话给{{1}}。
如果有的话,我会根据投票接受我或其他答案。