如何 return Observable 完成时的值?

How to return the value when Observable is complete?

我制作了这个 Observable 来压缩位图:

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? 
}

我的问题是我想 return Observable 完成时的结果:有办法吗?因为我可以在 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))

这样,您就有了一个方法来做一件事情(压缩位图),您可以在可观察链中使用它,而不会迷失在细节中或多次切换线程。