简体   繁体   中英

How to wait before another method is called with RxJava

For example I am starting a activity which finishes and returns a result, which is returned by the method onActivityResult . How can I wait before the result is provided by the onActivityResult and then continue my reactive stream?

public class TestActivity extends AppCompatActivity {

    ...

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // receiving result here
    }

    private Single<Data> loadData() {
        return Remote.getInstance().getData()
                .flatMap(data -> {
                    // do something
                    Intent intent = new Intent(TestActivity.this, OtherActivity.class);
                    startActivityForResult(intent, 0);

                }) // how can I receive the result from the onActivityResult here?
    }
}

It would be possible for example by using a PublishSubject that would notify in onActivityResult() and to which you'd flatMap() to in your original call, but I'd strongly advice against this. Here is why:

When your Activity receives an onActivityResult() , it might have been just recreated from scratch, because of a configuration change, memory pressure or anything else that happened in the meantime. This means that your Single subscription is either no longer active (if you properly unsubscribed from it onDestroy() or better in onStop() ) or leaked the previous activity instance to what it is still attached to (in case you did not unsubscribe).

So, instead the stream (and the aforementioned PublishSubject ) should probably live inside a component that survives activity recreation, like a retained fragment and you should call into that in onActivityResult() to notify your stream about the results. Here is some example how retained fragments and RxJava can work together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM