RxJava连锁呼叫延迟
问题描述:
mDisposable = mAdapter.getPublisher()
.subscribeOn(Schedulers.io())
.map(new Function<CreateVideoRx, CreateVideoRx>() {
@Override
public CreateVideoRx apply(CreateVideoRx createVideoRx) throws Exception {
Bitmap bitmap = mMediaMetadataRetriever.getFrameAtTime(createVideoRx.time * 1000000, MediaMetadataRetriever.OPTION_CLOSEST);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, 50, 90);
createVideoRx.mBitmap = bitmap;
return createVideoRx;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<CreateVideoRx>() {
@Override
public void accept(CreateVideoRx createVideoRx) throws Exception {
createVideoRx.mImageView.setImageBitmap(createVideoRx.mBitmap);
}
});
此RxJava连锁店的作品。但是我仍然在做一些错误的事情,因为它滞后,并且不觉得它在后台线程中工作。在这种情况下IO线程会做什么以及MainThread中会做什么?RxJava连锁呼叫延迟
我以前用AsyncTask做过这个。它运行良好,但现在我想跳过这个,并使用RxJava来代替。我有的结果是工作,但它滞后了很多。
编辑:增加了一些更多的信息
private final PublishSubject<CreateVideoRx> mPublisher = PublishSubject.create();
上述目的是所谓的mAdapter.getPublisher()
和本身看起来像
public PublishSubject<CreateVideoRx> getPublisher() {
return mPublisher;
}
我想要做的是对提取的缩略图功能后台线程。然后当它完成后,我希望它被推送到一个ImageView。
答
mDisposable = mAdapter.getPublisher()
.observeOn(Schedulers.io())
.map(new Function<CreateVideoRx, CreateVideoRx>() {
@Override
public CreateVideoRx apply(CreateVideoRx createVideoRx) throws Exception {
Bitmap bitmap = mMediaMetadataRetriever.getFrameAtTime(createVideoRx.time * 1000000, MediaMetadataRetriever.OPTION_CLOSEST);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, 50, 90);
createVideoRx.mBitmap = bitmap;
return createVideoRx;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<CreateVideoRx>() {
@Override
public void accept(CreateVideoRx createVideoRx) throws Exception {
createVideoRx.mImageView.setImageBitmap(createVideoRx.mBitmap);
}
});
这解决了我的问题。但我还是不明白,充分SubscribeOn和ObserveOn
答
之间的差异“在RxJava,你可以告诉你可观察到的代码线程使用subscribeOn()
运行的,和哪个线程的用户应该使用observeOn()
运行”。然而,这很复杂,因为运营商订阅源观察。
我记得subscribeOn()
影响函数上游的所有内容,而observeOn
影响函数下游的所有内容。你应该在原始问题上做的是
mDisposable = mAdapter.getPublisher()
.map(new Function<CreateVideoRx, CreateVideoRx>() {
@Override
public CreateVideoRx apply(CreateVideoRx createVideoRx) throws Exception {
Bitmap bitmap = mMediaMetadataRetriever.getFrameAtTime(createVideoRx.time * 1000000, MediaMetadataRetriever.OPTION_CLOSEST);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, 50, 90);
createVideoRx.mBitmap = bitmap;
return createVideoRx;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<CreateVideoRx>() {
@Override
public void accept(CreateVideoRx createVideoRx) throws Exception {
createVideoRx.mImageView.setImageBitmap(createVideoRx.mBitmap);
}
});
可能是由于'createVideoRx'上的竞争条件;看起来像你在多个线程之间共享相同的实例,而不是发送不可变数据,比如缩略图本身到GUI线程。 – akarnokd
你希望在io线程上完成哪些代码块? – yosriz
我希望我可以使第一个块在io线程中执行。但今天早上注意到两者都是主要执行的。 –