[英]RxJava chain calls lags
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中将执行什么操作?
我之前使用AsyncTask做到了。 它工作正常,但现在我想跳过它,改用RxJava。 我得到的结果是有效的,但它滞后很多。
编辑:添加了更多信息
private final PublishSubject<CreateVideoRx> mPublisher = PublishSubject.create();
上面的对象在mAdapter.getPublisher()
调用,函数本身看起来像
public PublishSubject<CreateVideoRx> getPublisher() {
return mPublisher;
}
我想要做的是在后台线程上提取缩略图。 然后,当完成时,我希望将其推送到单个ImageView。
“在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);
}
});
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之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.