resultLauncher
inline fun ComponentActivity.resultLauncher(crossinline onSuccess: () -> Unit = {}, crossinline onFailure: () -> Unit = {}): ActivityResultLauncher<Intent>
Creates an activity result launcher with typed success/failure callbacks.
This helper simplifies working with ActivityResultContracts.StartActivityForResult by providing a clean callback-based API. The launcher automatically determines success based on Activity.RESULT_OK.
Usage
class MainActivity : ComponentActivity() {
private lateinit var settingsLauncher: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsLauncher = resultLauncher(
onSuccess = {
showToast("Settings saved!")
},
onFailure = {
showToast("Settings cancelled")
}
)
// Later, launch the activity
val intent = Intent(this, SettingsActivity::class.java)
settingsLauncher.launch(intent)
}
}Content copied to clipboard
With ViewModel Integration
class MyViewModel : ViewModel() {
private val _settingsSaved = MutableSharedFlow<Unit>()
val settingsSaved = _settingsSaved.asSharedFlow()
fun onSettingsSaved() {
viewModelScope.launch {
_settingsSaved.emit(Unit)
}
}
}
// In Activity:
val launcher = resultLauncher(
onSuccess = { viewModel.onSettingsSaved() }
)Content copied to clipboard
Return
ActivityResultLauncher that can be used to launch intents
Parameters
onSuccess
Callback invoked when the activity returns Activity.RESULT_OK
onFailure
Callback invoked when the activity is cancelled or returns other result