Is there any default way to get the request code in ActivityResultContract
?
I know about StartActivityForResult
contract, which returns ActivityResult
, but there is no requestCode
, only resultCode
.
I can do something like this, but maybe there is a better solution:
class StartActivityForResult : ActivityResultContract<ActivityInput, ActivityOutput?>() {
override fun createIntent(
context: Context,
input: ActivityInput
): Intent {
return input.data.apply { putExtra(requestCodeKey, input.requestCode) }
}
override fun parseResult(resultCode: Int, intent: Intent?): ActivityOutput? {
return if (intent == null || resultCode != Activity.RESULT_OK) null
else ActivityOutput(
// should never return default value
requestCode = intent.getIntExtra(requestCodeKey, -1),
resultCode = resultCode,
data = intent
)
}
override fun getSynchronousResult(
context: Context,
input: ActivityInput?
): SynchronousResult<ActivityOutput?>? {
return if (input == null) SynchronousResult(null) else null
}
companion object {
const val requestCodeKey = "requestCodeKey";
}
}
data class ActivityInput(val requestCode: Int, val data: Intent)
data class ActivityOutput(val requestCode: Int,
val resultCode: Int,
val data: Intent
)