Android onActivityResult优雅的回调

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android onActivityResult优雅的回调相关的知识,希望对你有一定的参考价值。

青钢影说,优雅,永不过时

想优雅吗 赶紧拿起电脑访问:​​​​​​GitHub - VictorAlbertos/RxActivityResult: A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observable chain.

RxActivityResult

The api which android SDK exposes to retrieve the data from a 'returning system call' (camera, gallery, email...) just does not give a shit about Don't break the chain leitmotiv. Indeed, the OnActivityResult approach will break entirely your observable chaining.

I did this library to not have to deal with this OnActivityResult pattern. Never. Ever.

RxActivityResult features:

  • Launch the intent from any class, as long as you supply a valid Activity or Fragment instance.
  • Get the Intent back with the data encapsulated in an observable and keep going crazy chaining operators.

Setup

Add the JitPack repository in your build.gradle (top level module):

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

And add next dependencies in the build.gradle of the module:

dependencies {
    implementation 'com.github.VictorAlbertos:RxActivityResult:0.5.0-2.x'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
}

Usage

Call RxActivityResult.register in your Android Application class, supplying as parameter the current instance.

public class SampleApp extends Application {

    @Override public void onCreate() {
        super.onCreate();
        RxActivityResult.register(this);
    }
}

You can call RxActivityResult.on(this).startIntent(intent) supplying both, an Activity instance or a Fragment instance. Observe the emitted Result item to know the resultCode and retrieve the associated data if appropriate.

Limitation: Your fragments need to extend from androidx.fragment.app.Fragment instead of android.app.Fragment, otherwise they won't be notified.

Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

RxActivityResult.on(this).startIntent(takePhoto)
        .subscribe(result -> {
            Intent data = result.data();
            int resultCode = result.resultCode();
            // the requestCode using which the activity is started can be received here.
            int requestCode = result.requestCode();

            if(requestCode == YourActivity.YOUR_REQUEST_CODE)
            {
                // Do Something
            }

            if (resultCode == RESULT_OK) {
                result.targetUI().showImage(data);
            } else {
                result.targetUI().printUserCanceled();
            }
        });

是不是感觉脑袋瓜哇哇的根本看不懂

正常我们是访问一个intent

        .capture(false)
                .captureStrategy(false, getPackageName() + ".fileProvider", "kaikeba")
                .enableCorp(true)
                .start(REQUEST_CODE_CHOOSE);

传递一个 REQUEST_CODE_CHOOSE

然后再onActivityResult中处理返回的数据

这样非常的不优雅。

所以

我们可以使用这种方式

RxActivityResult.on(activity).startIntent(intent)
    public Observable<Result<Activity>> startByRxActivityResult() {
        Activity activity = mMatisse.getActivity();
        if (activity == null) {
            return null;
        }

        Intent intent = new Intent(activity, PictureSelectActivity.class);

       return RxActivityResult.on(activity).startIntent(intent);




    }

那么哎怎么处理失败呢?怎么更优雅那  用过rx的就知道

    Observable<Result<Activity>> rxRes =.....
 .enableCorp(true)
                    .startByRxActivityResult();                
.startByRxActivityResult();


            rxRes.subscribe(result -> {
                Intent data = result.data();
                int resultCode = result.resultCode();
                // the requestCode using which the activity is started can be received here.
                List<String> paths = KKBMatisse.obtainPathResult(data);
                if (paths != null && !paths.isEmpty()) {
                    String picturePath = paths.get(0);
                    Log.e(TAG, "startByRxActivityResult: " + picturePath);
                    bridge.onCallback(picturePath);
                } else {
                    Log.e(TAG, "startByRxActivityResult: null");
                    bridge.onCallback("");

                }

            });

你会惊讶的发现少了REQUEST_CODE_CHOOSE 但是没有处理失败

rx用法也没有lin

以上是关于Android onActivityResult优雅的回调的主要内容,如果未能解决你的问题,请参考以下文章

Android基础:startActivityForResult 和 onActivityResult 问题

android中onActivityResult的用途是啥[重复]

Android - 片段的 onActivityResult() 中的 NPE

片段中的Android onActivityResult

片段android中未调用onActivityResult [重复]

Android基础篇 onActivityResult