Instantly share code, notes, and snippets.

Embed
What would you like to do?
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import kotlinx.coroutines.experimental.suspendCancellableCoroutine
typealias RequestCode = Int
typealias ResultCode = Int
data class ActivityResult(
val requestCode: RequestCode,
val resultCode: ResultCode,
val data: Intent?
)
object MutableRelay {
var request: Intent? = null
var result: ((ActivityResult) -> Unit)? = null
}
val REQUEST_CODE = 1337
class ResultActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MutableRelay.request
?.let { startActivityForResult(it, REQUEST_CODE) }
?: finish()
}
override fun onActivityResult(requestCode: RequestCode, resultCode: ResultCode, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
finish()
if (requestCode == REQUEST_CODE) {
MutableRelay.result?.let {
it(ActivityResult(requestCode = requestCode,
resultCode = resultCode,
data = data))
}
}
}
}
suspend fun Activity.awaitActivityForResult(intent: Intent): ActivityResult =
suspendCancellableCoroutine { cont ->
cont.invokeOnCompletion {
MutableRelay.request = null
MutableRelay.result = null
}
MutableRelay.request = intent
MutableRelay.result = { cont.resume(it) }
startActivity(Intent(this, ResultActivity::class.java))
}
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment