Last active
December 4, 2020 02:10
-
-
Save dokinkon/4da0630811cb99aa563a4a2fd525f512 to your computer and use it in GitHub Desktop.
suspend activityForResult
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wraps the parameters of onActivityResult | |
* | |
* @property resultCode the result code returned from the activity. | |
* @property data the optional intent returned from the activity. | |
* @since 0.0.3 | |
*/ | |
data class ActivityResult( | |
val requestCode: Int, | |
val resultCode: Int, | |
val data: Intent?) { | |
/** | |
* | |
*/ | |
val isOk: Boolean = (resultCode == Activity.RESULT_OK) | |
} | |
abstract class CYCompatActivity : AppCompatActivity(), CoroutineScope by MainScope() { | |
private val resultByCode = mutableMapOf<Int, CompletableDeferred<ActivityResult?>>() | |
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { | |
resultByCode[requestCode]?.let { | |
it.complete( | |
ActivityResult( | |
requestCode = requestCode, | |
resultCode = resultCode, | |
data = data | |
) | |
) | |
resultByCode.remove(requestCode) | |
} ?: run { | |
super.onActivityResult(requestCode, resultCode, data) | |
} | |
} | |
override fun onDestroy() { | |
super.onDestroy() | |
cancel() | |
} | |
/** | |
* | |
*/ | |
suspend fun awaitActivityForResult(requestCode: Int, intent: Intent): ActivityResult? { | |
val activityResult = CompletableDeferred<ActivityResult?>() | |
if (intent.resolveActivity(packageManager) != null) { | |
resultByCode[requestCode] = activityResult | |
startActivityForResult(intent, requestCode) | |
} else { | |
activityResult.complete(null) | |
} | |
return activityResult.await() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment