Skip to content

Instantly share code, notes, and snippets.

@KaustubhPatange
Created February 23, 2022 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KaustubhPatange/bb70d2bfdacfe6cbea077f73c492e975 to your computer and use it in GitHub Desktop.
Save KaustubhPatange/bb70d2bfdacfe6cbea077f73c492e975 to your computer and use it in GitHub Desktop.
Some extension methods to use ActivityResult API in a callback way.
package com.kpstv.xclipper.extensions
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import java.util.*
/**
* Start an activity for result where the result will be called on the [onActivityResult] lambda.
*
* Instead of calling result on `onActivityResult(...)`, they will be invoked on [onActivityResult].
*/
fun ComponentActivity.startActivityWithResult(
input: Intent,
onActivityResult: (ActivityResult) -> Unit
) : Unit = launchContractWithResult(input, ActivityResultContracts.StartActivityForResult(), onActivityResult)
/**
* Start an activity for result where the result will be called on the [onActivityResult] lambda.
*
* Instead of calling result on `onActivityResult(...)`, they will be invoked on [onActivityResult].
*/
fun Fragment.startActivityWithResult(
input: Intent,
onActivityResult: (ActivityResult) -> Unit
) : Unit = requireActivity().startActivityWithResult(input, onActivityResult)
/**
* Execute [input] through a given [contract] where the result will be called on the [onResult] lambda.
*/
fun <I, O> ComponentActivity.launchContractWithResult(
input: I,
contract: ActivityResultContract<I, O>,
onResult: (O) -> Unit
) {
register
val contractKey = "contract_${UUID.randomUUID()}"
var launcher: ActivityResultLauncher<I?>? = null
launcher = activityResultRegistry.register(contractKey, contract) { result ->
launcher?.unregister()
onResult(result)
}
launcher.launch(input)
}
/**
* Execute [input] through a given [contract] where the result will be called on the [onResult] lambda.
*/
fun <I, O> Fragment.launchContractWithResult(
input: I,
contract: ActivityResultContract<I, O>,
onResult: (O) -> Unit
) {
requireActivity().launchContractWithResult(
input = input,
contract = contract,
onResult = onResult
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment