我正在尝试使用 OkHttp 下载文件并使用 Okio 写入磁盘。我还为这个过程创建了一个 rx observable。它正在工作,但是它明显比我以前使用的(Koush 的 Ion 库)慢。
这是我创建可观察对象的方法:
public Observable<FilesWrapper> download(List<Thing> things) {
return Observable.from(things)
.map(thing -> {
File file = new File(getExternalCacheDir() + File.separator + thing.getName());
if (!file.exists()) {
Request request = new Request.Builder().url(thing.getUrl()).build();
Response response;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) new IOException();
else {
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
}
} catch (IOException e) {
new IOException();
}
}
return file;
})
.toList()
.map(files -> new FilesWrapper(files);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道是什么原因导致速度变慢,或者我是否错误地使用了操作员?
我需要从 JSon 提要加载数据(最多 22,000 条记录)并将它们存储在我的 android 设备上(在 SQLite 中)。
单独插入很容易实现,但速度很慢。理想情况下,我想批量插入对象并将这些对象的列表传递给数据库。
我可以看到如何强制执行,但我真的很想用 RxJava 来做,但不确定如何做。
谢谢
我已经开始研究retrolambda 和rxjava。我自己转换了一些表达式,但其中一些我无法转换。我已将 retrolambda 添加到我的项目中。这里是示例
public Observable<ImmutableList<Repository>> getUsersRepositories() {
return githubApiService.getUsersRepositories(user.login)
.map(repositoryResponses -> {
final ImmutableList.Builder<Repository> listBuilder = ImmutableList.builder();
for (RepositoryResponse repositoryResponse : repositoryResponses) {
Repository repository = new Repository();
repository.id = repositoryResponse.id;
repository.name = repositoryResponse.name;
repository.url = repositoryResponse.url;
listBuilder.add(repository);
}
return listBuilder.build();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何转换这种代码的和平:
obs.subscribe(new Observer<List<Integer>>() {
public void onCompleted() {
System.out.println("completed");
}
public void onError(Throwable e) {
System.out.println("failure");
}
public void onNext(List<Integer> value) {
System.out.println("onnext=" + value);
}
});
Run Code Online (Sandbox Code Playgroud) 我有这样的 JSON:
{
"success":true,
"data":[
{
"id":"29",
"name":"\u0420\u0435\u0441\u0442\u043e\u0440\u0430\u0446\u0456\u044f \u0411\u0430\u0447\u0435\u0432\u0441\u044c\u043a\u0438\u0445 \/ Baczewski Restaurant",
"street":"\u0432\u0443\u043b. \u0428\u0435\u0432\u0441\u044c\u043a\u0430, 8",
"latitude":"49.842292845502",
"longitude":"24.029848249565",
"image":"https:\/\/i.onthe.io\/j9aocq72r2lfsmoh9.r500x500.01ff9fff.jpg"
},
...
]
}
Run Code Online (Sandbox Code Playgroud)
根据它必须 Classes(pojo)用模式创建到pojo。第一个提供了从data数组中获取数据的方法 - >
public List<Datum> getData() {
return data;
}
Run Code Online (Sandbox Code Playgroud)
第二个是model 这个数据的一个。
在仅使用改造 2.0 时,我执行 a call,object 从 data数组中解析每个并将其添加到RecyclerView.Adapter
Call<PlaceList> call = service.list(1, offset, 10);
call.enqueue(new Callback<PlaceList>() {
@Override
public void onResponse(Call<PlaceList> call, Response<PlaceList> response) {
final int size = response.body().getData().size();
for (int i = 0; i < size; …Run Code Online (Sandbox Code Playgroud) 我有一个非常标准的 API 分页问题,您可以通过一些简单的递归来处理。这是一个虚构的例子:
public Observable<List<Result>> scan() {
return scanPage(Optional.empty(), ImmutableList.of());
}
private Observable<?> scanPage(Optional<KEY> startKey, List<Result> results) {
return this.scanner.scan(startKey, LIMIT)
.flatMap(page -> {
if (!page.getLastKey().isPresent()) {
return Observable.just(results);
}
return scanPage(page.getLastKey(), ImmutableList.<Result>builder()
.addAll(results)
.addAll(page.getResults())
.build()
);
});
}
Run Code Online (Sandbox Code Playgroud)
但这显然会创建一个庞大的调用堆栈。如何强制执行此操作但维护 Observable 流?
这是一个命令式阻塞示例:
public List<Result> scan() {
Optional<String> startKey = Optional.empty();
final ImmutableList.Builder<Result> results = ImmutableList.builder();
do {
final Page page = this.scanner.scan(startKey);
startKey = page.getLastKey();
results.addAll(page.getResults());
} while (startKey.isPresent());
return results.build();
}
Run Code Online (Sandbox Code Playgroud) 我有一个网络调用来验证和接收一个令牌,另一个使用这个令牌请求数据。
我想将它们组合成一个Single<Data>. 为此,我正在查看concat,但这似乎仅适用于Observable相同类型。使用zipI 可以只返回第二个的响应Observable,但据我所知,它可以并行工作,而我需要等待第一个Observable并在我开始第二个之前处理它的响应。
在这种情况下,我应该使用什么运算符?
我正在尝试在 RxJava2 中实现一个简单的滑动窗口函数,但正在努力做我想做的事。
我的目标是获取对象流,即
["a", "b", "c", "d", "e"]
Run Code Online (Sandbox Code Playgroud)
并应用一个滑动窗口,它将返回与每个元素相邻的元素。
即导致:
["a", "b"]
["a", "b", "c"]
["b", "c", "d"]
["c", "d", "e"]
["d", "e"].
Run Code Online (Sandbox Code Playgroud)
IE
a----------------b----------------c----------------d----------------e
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?
["a", "b"] ["a", "b", "c"] ["b", "c", "d"] ["c", "d", "e"] ["d", "e"]
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄清楚如何做到这一点。Google Groups 帖子似乎走在正确的轨道上,但并没有得到我需要的结果:https : //groups.google.com/forum/#!topic/rxjava/k-U5BijXinU
有任何想法吗?
我有一个生产者(使用 Kafka)和不止一个消费者。所以我在一个主题中发布一条消息,然后我的消费者接收并处理该消息。
我需要在生产者中收到至少一个消费者的响应(如果是第一个消费者会更好)。我正在尝试使用 RxJava 来做到这一点(可观察的)。
可以这样做吗?有人有例子吗?
我开始使用 RXAndroid 并且我已经发布了我的第一个测试版,但出现了一个我没想到的异常。我确定这是因为我对onError方法的工作原理缺乏了解。
我的代码是这样的:
disposables.add(Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
if (e.isDisposed()) {
return;
}
//do stuff
if (stuff didn't fail) {
e.onNext(myString);
} else {
e.onError(new Exception("stuff failed"));
}
e.onComplete();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<String>() {
@Override
public void onNext(@NonNull String myString) {
//do stuff
}
@Override
public void onError(@NonNull Throwable e) {
//handle the error
}
@Override
public void onComplete() {
}
})
);
Run Code Online (Sandbox Code Playgroud)
我在这里崩溃了:
e.onError(new Exception("stuff failed"));
但我个人认为这可以处理这种情况? …
我是RxJava的新手,我需要以异步方式使用Observable功能.
我还需要使用超时:在我的例子中,我希望每个进程在1秒或更短的时间内结束.
这就是我现在所做的:
public static void hello(String name) throws IOException {
Observable<String> obs2 = Observable.just(name).timeout(1000, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io());
obs2.subscribe(new Action1<String>() {
@Override
public void call(String s) {
if("CCCCC".equals(s)){
try {
Thread.sleep(3200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s + " " + new Date() +" "+Thread.currentThread().getName());
}
});
}
public static void main(final String[] args) throws InterruptedException, IOException {
hello("AAAAA");
hello("CCCCC");
hello("BBBBBB");
System.in.read();
}
Run Code Online (Sandbox Code Playgroud)
结果:
AAAAA Thu Oct 05 09:43:46 CEST 2017 RxIoScheduler-2
BBBBBB Thu Oct 05 09:43:46 CEST 2017 …Run Code Online (Sandbox Code Playgroud) rx-java ×10
java ×5
android ×3
reactivex ×2
rx-android ×2
apache-kafka ×1
json ×1
observable ×1
okhttp ×1
okio ×1
pagination ×1
retrofit2 ×1
retrolambda ×1
rx-java2 ×1
sqlite ×1
timeout ×1