dependencies {
...
implementation 'com.afollestad.inline-activity-result:core:0.2.0'
}
You call startActivityForResult
, providing the Activity to launch as the generic type. You
receive the result in a callback without having to override onActivityResult
. And, you don't
have to worry about requestCode
or resultCode
.
class NewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras = Bundle()
.putString("some_extra", "Hello, World!")
startActivityForResult<OtherActivity>(extras) { success, data ->
if (success) {
toast("Got successful result: $data")
}
}
}
}
There are multiple variants startActivityForResult
you can use for different use cases. All of
them allow you to pass an optional requestCode
parameter, but this should generally be unnecessary.
First, the simplest you can get is just a generic type and the callback.
startActivityForResult<OtherActivity> { success, data ->
// Do something
}
Second, you can provide a Bundle
of extras to the destination Activity:
val extras = Bundle()
.putString("some_extra", "Hello, World!")
startActivityForResult<OtherActivity>(extras) { success, data ->
// Do something
}
And finally, you can use a full intent. In this variant you do not provide a generic parameter.
val intent = Intent(Intent.ACTION_VIEW)
.setData("content://some-uri".toUri())
startActivityForResult(intent) { success, data ->
// Do something
}
dependencies {
...
implementation 'com.afollestad.inline-activity-result:coroutines:0.2.0'
}
You can use Kotlin coroutines to get rid of the callback. It of course is a suspend function so it must be called within a coroutine scope.
Instead of startActivityForResult
, you can use startActivityAwaitResult
:
val result: ActivityResult = startActivityAwaitResult<OtherActivity>()
// use result...
dependencies {
...
implementation 'com.afollestad.inline-activity-result:rxjava:0.2.0'
}
You can use RxJava to integrate the Activity launch and result into your streams.
Instead of startActivityForResult
, you can use startActivityEmitResult
:
val disposable = startActivityEmitResult<OtherActivity>()
.subscribe { result ->
// use result...
}
// make sure you dispose of the subscription when your Activity/Fragment goes away
disposable.dispose()