SafeBundle
๐ฆ
๋ชฉ์
์ด ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ชฉ์ ์ Activity/Fragment๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ ๋ ์ฌ์ฉํ๋ Bundle์ ๊ฐ์ ์ฌ๋ฐ๋ฅด๊ฒ ๋ฃ๊ณ , ๊ทธ๊ฒ์ ๋ง๊ฒ ๊บผ๋ด์ ์ฌ์ฉํ๋์ง ์ปดํ์ผ ํ์์ ํ์ธํ์ฌ ๋ฐํ์ ์๋ฌ๋ฅผ ๋ฏธ์ฐ์ ๋ฐฉ์ง ํ๋ ๊ฒ
class MyActivity1: AppCompatActivity() {
...
fun startMyActivity2() {
val intent = Intent(this, MyActivity2::class.java).apply {
putExtra("param", "str")
}
startActivity(intent)
}
...
}
class MyActivity2: AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
// wrong key value
val param = intent.extras?.get("wrong key") as String -> Runtime Error
// wrong type casting
val param = intent.extras?.get("param") as Int -> Runtime Error
}
}
์์ ๊ฐ์ด ๊ฐ๋ฐ์๊ฐ ์ค์๋ฅผ ํ ๊ฒฝ์ฐ ๋ฐํ์์ ๋ฒ๊ทธ๋ฅผ ์ ์ ์์ผ๋ฏ๋ก ์ํํ๋ค.
์ฌ์ฉ๋ฒ
0. ์์กด์ฑ ์ค์
SafeBundle ์์กด์ฑ ๋ฑ๋ก
implementation "io.github.sabgilhun:safebundle:x.y.z"
implementation "io.github.sabgilhun:safebundle-annotation:x.y.z"
kapt "io.github.sabgilhun:safebundle-processor:x.y.z"
ํ์ฌ ๋ฒ์ (0.2.1)
1. ์ ๋ฌ ๋ฐ์ ์ธ์ ์ค์
Activity์์ ๋ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ธ์๋ค์ ๋ฉค๋ฒ ๋ณ์ ์ ์ํ๊ณ by bundle<Type>()๋ก property delegation ํ๋ค.
class ReceiveActivity: AppCompatActivity() {
private val p1 by bundle<Int>()
private val p2 by bundle<String?>()
}
2. Activity๋ฅผ ์์ ํ๋ Navgator์ ์
Activity๋ฅผ ์ด๋ค ์ธ์๋ก ์์ํ ์ง ์ ์ํ Navigator๋ฅผ ์์ฑํ๋ค.
// Navigator๋ interface์ฌ์ผ ํ๋ฉฐ ContextBasedCreatable์ ํ์ฅํด์ผ ํ๋ค.
interface Navigator : ContextBasedCreatable {
// ReciveActivity์์ ์ ์ํ ๋ฉค๋ฒ ๋ณ์๋ค์ ๋ณ์๋ช
๊ณผ ํ์
๊ณผ ์ผ์นํด์ผ ํ๋ค.
// p1 - Int, p2 - String?
fun start(p1: Int, p2: String?) // return ํ์
์ Unit์ด์ฌ์ผ ํ๋ค.
// p2๋ Nullableํ๊ธฐ ๋๋ฌธ์ ์ธ์๋ฅผ ์์ ์์ฐ๋ ํจ์ ์ ์๋ ๊ฐ๋ฅํ๋ค.
fun start(p1: Int)
// ๋ฐ๋์ชฝ์ p2๋ Nullableํ๊ธฐ ๋๋ฌธ์ ์ถฉ๋ถ ์กฐ๊ฑด์ธ p2๊ฐ NonNullํ ํจ์ ์ ์๋ ๊ฐ๋ฅํ๋ค.
fun start(p1: Int, p2: String)
}
3. Activity์ Navgator ์ฐ๊ฒฐ
Activity์ ํด๋น Activity๊ฐ ์ด๋ค ์ธ์๋ค๋ก ์์๋ ์ ์๋์ง ์ ์ํ Navigator๋ฅผ SafeBundle ์ด๋
ธํ
์ด์
์ผ๋ก ์ฐ๊ฒฐํด์ฃผ์ด์ผ ์ปดํ์ผ ํ์์ ์ ํฉ์ฑ ์ฒดํฌ๋ฅผ ํ ์ ์๋ค.
@SafeBundle(Navigator::class) // ์ด์ค ์ถ๊ฐ
class ReceiveActivity: AppCompatActivity() {
private val p1 by bundle<Int>()
private val p2 by bundle<String?>()
}
4. Navgator๋ฅผ ํตํด Activity ์คํ
class MainActivity: AppCompatActivity() {
private val navigator = create<Navigator>() // Activity Extension function์ธ create() ์ฌ์ฉ
fun startReceiveActivity() {
navigator.start(1, "p2")
}
...
}
License
SafeBundle is under MIT License. (detail)