我已经使这个Observable压缩了Bitmap:
public static Uri compressBitmapInBackground(Bitmap original, Context context)
{
Uri value;
Observable.create((ObservableOnSubscribe<Uri>) e ->
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),decoded, "Title", null);
Log.d("pathCompress",path);
Uri uriPath = Uri.parse(path);
e.onNext(uriPath);
e.onComplete();
}).subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(x-> System.out.print(x) );
//how to return x when observable is complete?
}
我的问题是我想在Observable完成时返回结果:有没有办法做到这一点?因为我可以在onNext()上调用我的函数中的演示者,但我更愿意避免它。
谢谢
答案 0 :(得分:1)
我认为你在混淆问题。我将概念分为:
public static Uri compressBitmap(Bitmap original, Context context) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),decoded, "Title", null);
Log.d("pathCompress",path);
Uri uriPath = Uri.parse(path);
}
然后在可观察的流程中使用此方法:
Observable
.from(...)
.map(foo -> getBitmap(bar))
.observeOn(Schedulers.computation())
.map(bitmap -> compressBitmap(bitmap,context))
.doOnNext(url -> dowhatever(url))
通过这种方式,您可以使用单个方法执行单个操作(压缩位图),并且可以在可观察链中使用它,而不会丢失细节或切换线程很多次。