我正在尝试处理对象流(通过http JSon请求)。
Observble会返回以下内容:
“2015-05-06T13:24:20Z”,Foo,Foo,1,2,3,Foo,Foo
第一项是时间戳,然后Foo对象存储在db中,然后id表示需要从db中删除的Foo对象,最后是需要更新的Foo对象(我要做一个为他们竖起来。)
我目前的实现如下:
public void updateFoos(final CallBack callBack) {
final String lastFooUpdateTimestamp = localStorage.getLastFooUpdateTimestamp();
fooService.getFoos(lastFooUpdateTimestamp)
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
callBack.onSuccess();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Object o) {
if (o instanceof String) {
localStorage.setLastFooUpdateTimestamp((String) o);
}
if (o instanceof Foo) {
databaseManager.save((Foo) o);
}
}
});
}
有很多问题:
答案 0 :(得分:4)
以下是使用RxJava如何完成的示例:
public class MultikindSource {
enum ValueType {
TIMESTAMP,
NUMBER,
FOO
}
static final class Foo { }
static Observable<Object> source(String timestamp) {
return Observable.from(Arrays.asList(timestamp, new Foo(), new Foo(),
1, 2, 3, new Foo()));
}
public static void main(String[] args) {
Func1<Object, ValueType> keySelector = o -> {
if (o instanceof String) {
return ValueType.TIMESTAMP;
} else
if (o instanceof Foo) {
return ValueType.FOO;
}
return ValueType.NUMBER;
};
AtomicReference<String> lastTimestamp = new AtomicReference<>(
"2015-05-08T11:38:00.000Z");
source(lastTimestamp.get())
.groupBy(keySelector)
.flatMap(g -> {
if (g.getKey() == ValueType.TIMESTAMP) {
g.subscribe(v -> {
System.out.println("Updating timestamp to " + v);
lastTimestamp.set((String)v);
});
} else
if (g.getKey() == ValueType.FOO) {
g.buffer(2).subscribe(v ->
System.out.println("Batch inserting " + v));
} else {
g.subscribe(v ->
System.out.println("Got some number: " + v));
}
return Observable.just(1);
}).count().subscribe(v ->
System.out.println("Got " + v + " kinds of events."));
}
}
基本上,您按照某些枚举对源数据进行分组,然后链接到这些组并订阅它们以执行工作。