Skip to content

Instantly share code, notes, and snippets.

@randallmitchell
Created April 19, 2018 22:16
Show Gist options
  • Save randallmitchell/52d7b411ba55f02db02e8fbd95762abf to your computer and use it in GitHub Desktop.
Save randallmitchell/52d7b411ba55f02db02e8fbd95762abf to your computer and use it in GitHub Desktop.
Android Functional Activity Approach
package com.methodsignature.kotlin.example
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
/**
* Base class that supports composition and handles the boilerplate.
*/
open class BaseActivity: AppCompatActivity() {
private val activityResultHandlers = mutableMapOf<Int, (Int, Intent?) -> Unit>()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
activityResultHandlers[requestCode]?.apply {
invoke(resultCode, data)
}
}
fun addActivityResultHandler(requestCode: Int, action: (Int, Intent?) -> Unit) {
activityResultHandlers[requestCode] = action
}
}
/**
* Worker Activity
*/
class SomeActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent(this, SomeOtherActivity::class.java)
addActivityResultHandler(REQUEST_DO_SOME_WORK, toastActivityResult)
startActivityForResult(intent, REQUEST_DO_SOME_WORK)
}
private val toastActivityResult: (Int, Intent?) -> Unit = { resultCode, _ ->
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Result was a success", Toast.LENGTH_SHORT).show()
}
}
companion object {
const val REQUEST_DO_SOME_WORK = 5738
}
}
/**
* Just here for reference.
*/
class SomeOtherActivity: AppCompatActivity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment