Android 当Observable完成时,如何返回值?
为了压缩位图,我将此设置为可观察:Android 当Observable完成时,如何返回值?,android,rx-java,rx-java2,Android,Rx Java,Rx Java2,为了压缩位图,我将此设置为可观察: public static Uri compressBitmapInBackground(Bitmap original, Context context) { Uri value; Observable.create((ObservableOnSubscribe<Uri>) e -> { ByteArrayOutputStream out = new ByteArrayOutputStream();
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?
}
我的问题是,我想在可观察对象完成后返回结果:有没有办法?因为我可以通过onNext上的函数调用演示者,但我更愿意避免它
谢谢你我想你的担心混杂在一起了。我将这些概念分为:
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))
这样,您就有了一个方法,可以对位图进行单一的压缩,并且您可以在可观察链中使用它,而不会迷失在细节中,也不会多次切换线程。有趣的是……我编写的最后一个代码仅用于生成可重用代码,但我只能重用该函数,并在我需要的每个类中实现可观察性,是吗?确切地说-因为在每种情况下,需要压缩多少位图与更新显示、在线/离线/后台处理等的频率不同,所以通常最好进行自包含的处理,然后将它们绑在需要使用它们的每个位置。