สูตรการนำทางแบบโมดูลาร์ (Hilt)
สูตรนี้แสดงวิธีจัดโครงสร้างแอปพลิเคชันแบบหลายโมดูลโดยใช้ Navigation 3 และ Dagger/Hilt สำหรับการแทรก Dependency เป้าหมายคือการสร้างสถาปัตยกรรมแบบแยกส่วนซึ่งมีการกำหนดและใช้การนำทางในโมดูลฟีเจอร์ที่แยกต่างหาก
วิธีการทำงาน
แอปพลิเคชันแบ่งออกเป็นหลายโมดูล ดังนี้
-
โมดูล
app: โมดูลแอปพลิเคชันหลัก โดยมีHiltDeepLinkActivity(จุดแรกเข้าที่แสดงการเปิด Intent ของ Deep Link แบบปกติและแบบชัดเจน),HiltModularActivity(ซึ่งโฮสต์NavDisplayและมอบสิทธิ์ Intent ของ Deep Link ให้กับNavigator.handleDeepLink(intent)), การเชื่อมโยงปลายทางเริ่มต้น และสร้างentryProviderสุดท้าย -
โมดูล
common: โมดูลนี้มีตรรกะการนำทางหลัก ซึ่งรวมถึงรายการต่อไปนี้- คลาส
Navigatorที่จัดการ Back Stack, แก้ไข Intent ของ Deep Link ขาเข้า และสร้าง Back Stack สังเคราะห์ผ่านhandleDeepLink(intent) startDestination: NavKeyที่ใช้เพื่อเริ่มต้น Back Stack- ประเภท
EntryProviderInstallerซึ่งเป็นฟังก์ชันที่โมดูลฟีเจอร์ใช้เพื่อส่งรายการการนำทางไปยังentryProviderของแอปพลิเคชัน BackStackMatcher<*, NavKey>ซึ่งโมดูลฟีเจอร์ใช้เพื่อส่งตัวจับคู่ Deep Link ที่มี Back Stack สังเคราะห์
- คลาส
-
โมดูลฟีเจอร์ (เช่น
conversation,profile): ฟีเจอร์แต่ละรายการจะแบ่งออกเป็น 2 โมดูลย่อย ดังนี้- โมดูล
api: กำหนด API สาธารณะสำหรับฟีเจอร์ รวมถึงเส้นทางการนำทางและรูปแบบ URI ของ Deep Link ซึ่งจะช่วยให้โมดูลอื่นๆ ไปยังฟีเจอร์นี้ได้โดยไม่ต้องทราบรายละเอียดการติดตั้งใช้งาน - โมดูล
impl: มีการติดตั้งใช้งานฟีเจอร์ รวมถึง Composable,EntryProviderInstallerที่แมปเส้นทางของฟีเจอร์กับ Composable และBackStackMatcher<*, NavKey>ที่กำหนดค่าด้วย.withBackStackเพื่อสร้าง Back Stack ตามลำดับชั้นที่เหมาะสม (เช่น[ConversationList, ConversationDetail(id)]) โดยทั้ง 2 อย่างนี้จะใช้การเชื่อมโยงหลายรายการของ Dagger/Hilt (@IntoSet)
- โมดูล
แนวทางแบบโมดูลาร์นี้ช่วยให้แยกข้อกังวลได้อย่างชัดเจน ทำให้ฐานของโค้ดปรับขนาดและบำรุงรักษาได้ง่ายขึ้น แต่ละฟีเจอร์มีหน้าที่รับผิดชอบตรรกะการนำทางของตนเอง และโมดูล app จะรวมส่วนต่างๆ เหล่านี้เข้าด้วยกันเท่านั้น
package com.example.nav3recipes.modular.hilt import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.deeplink.BackStackMatcher import androidx.navigation3.runtime.deeplink.DeepLinkUri import androidx.navigation3.runtime.deeplink.UriDeepLinkMatcher import androidx.navigation3.runtime.deeplink.withBackStack import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.multibindings.IntoSet import kotlinx.serialization.Serializable // API @Serializable object Profile : NavKey const val PROFILE_URI = "https://www.nav3recipes.com/profile" // IMPLEMENTATION @Module @InstallIn(ActivityRetainedComponent::class) object ProfileModule { @IntoSet @Provides fun provideEntryProviderInstaller() : EntryProviderInstaller = { entry<Profile>{ ProfileScreen() } } @IntoSet @Provides fun provideDeepLinkMatcher(): BackStackMatcher<*, NavKey> = UriDeepLinkMatcher( uriPattern = DeepLinkUri(PROFILE_URI), serializer = Profile.serializer(), ).withBackStack { matchResult -> listOf(ConversationList, matchResult.key) } } @Composable private fun ProfileScreen() { val profileColor = MaterialTheme.colorScheme.surfaceVariant Column( modifier = Modifier .fillMaxSize() .background(profileColor) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = "Profile Screen", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurface ) } }
package com.example.nav3recipes.modular.hilt import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.lifecycle.compose.dropUnlessResumed import com.example.nav3recipes.ui.setEdgeToEdgeConfig class HiltDeepLinkActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setEdgeToEdgeConfig() setContent { Scaffold { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Button( onClick = dropUnlessResumed { val intent = Intent( this@HiltDeepLinkActivity, HiltModularActivity::class.java, ) startActivity(intent) } ) { Text("Conversation List") } Spacer(modifier = Modifier.height(24.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(24.dp)) var conversationId by remember { mutableStateOf("") } OutlinedTextField( value = conversationId, onValueChange = { conversationId = it }, label = { Text("Conversation Number") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), ) Spacer(modifier = Modifier.height(16.dp)) Button( enabled = conversationId.toIntOrNull() != null, onClick = dropUnlessResumed { val intent = Intent( this@HiltDeepLinkActivity, HiltModularActivity::class.java, ).apply { data = "$CONVERSATION_URI/$conversationId".toUri() } startActivity(intent) } ) { Text("Deep Link to Conversation") } Spacer(modifier = Modifier.height(24.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(24.dp)) Button( onClick = dropUnlessResumed { val intent = Intent( this@HiltDeepLinkActivity, HiltModularActivity::class.java, ).apply { data = PROFILE_URI.toUri() } startActivity(intent) } ) { Text("Deep Link to Profile") } } } } } }
package com.example.nav3recipes.modular.hilt import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.ui.Modifier import androidx.navigation3.runtime.entryProvider import androidx.navigation3.ui.NavDisplay import com.example.nav3recipes.ui.setEdgeToEdgeConfig import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class HiltModularActivity : ComponentActivity() { @Inject lateinit var navigator: Navigator @Inject lateinit var entryProviderScopes: Set<@JvmSuppressWildcards EntryProviderInstaller> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setEdgeToEdgeConfig() navigator.handleDeepLink(intent) setContent { Scaffold { paddingValues -> NavDisplay( backStack = navigator.backStack, modifier = Modifier.padding(paddingValues), onBack = { navigator.goBack() }, entryProvider = entryProvider { entryProviderScopes.forEach { builder -> this.builder() } } ) } } } }
package com.example.nav3recipes.modular.hilt import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Button import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.dropUnlessResumed import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.deeplink.BackStackMatcher import androidx.navigation3.runtime.deeplink.DeepLinkUri import androidx.navigation3.runtime.deeplink.UriDeepLinkMatcher import androidx.navigation3.runtime.deeplink.withBackStack import com.example.nav3recipes.ui.theme.colors import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.multibindings.IntoSet import kotlinx.serialization.Serializable // API object ConversationList : NavKey @Serializable data class ConversationDetail(val id: Int) : NavKey { val color: Color get() = colors[id % colors.size] } const val CONVERSATION_URI = "https://www.nav3recipes.com/conversation" // IMPL @Module @InstallIn(ActivityRetainedComponent::class) object ConversationModule { @IntoSet @Provides fun provideEntryProviderInstaller(navigator: Navigator): EntryProviderInstaller = { entry<ConversationList> { ConversationListScreen( onConversationClicked = { conversationDetail -> navigator.goTo(conversationDetail) } ) } entry<ConversationDetail> { key -> ConversationDetailScreen(key) { navigator.goTo(Profile) } } } @IntoSet @Provides fun provideDeepLinkMatcher(): BackStackMatcher<*, NavKey> = UriDeepLinkMatcher( uriPattern = DeepLinkUri("$CONVERSATION_URI/{id}"), serializer = ConversationDetail.serializer(), ).withBackStack { matchResult -> listOf(ConversationList, matchResult.key) } } @Composable private fun ConversationListScreen( onConversationClicked: (ConversationDetail) -> Unit ) { LazyColumn( modifier = Modifier.fillMaxSize(), ) { items(10) { index -> val conversationId = index + 1 val conversationDetail = ConversationDetail(conversationId) val backgroundColor = conversationDetail.color ListItem( modifier = Modifier .fillMaxWidth() .clickable(onClick = dropUnlessResumed { onConversationClicked(conversationDetail) }), headlineContent = { Text( text = "Conversation $conversationId", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onSurface ) }, colors = ListItemDefaults.colors( containerColor = backgroundColor // Set container color directly ) ) } } } @Composable private fun ConversationDetailScreen( conversationDetail: ConversationDetail, onProfileClicked: () -> Unit ) { Column( modifier = Modifier .fillMaxSize() .background(conversationDetail.color) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = "Conversation Detail Screen: ${conversationDetail.id}", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurface ) Spacer(modifier = Modifier.height(16.dp)) Button(onClick = dropUnlessResumed(block = onProfileClicked)) { Text("View Profile") } } }
package com.example.nav3recipes.modular.hilt import android.content.Intent import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.navigation3.runtime.EntryProviderScope import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.deeplink.BackStackMatcher import androidx.navigation3.runtime.deeplink.DeepLinkRequest import androidx.navigation3.runtime.deeplink.invoke import dagger.hilt.android.scopes.ActivityRetainedScoped import javax.inject.Inject typealias EntryProviderInstaller = EntryProviderScope<NavKey>.() -> Unit @ActivityRetainedScoped class Navigator @Inject constructor( startDestination: NavKey, private val deepLinkMatchers: Set<@JvmSuppressWildcards BackStackMatcher<*, NavKey>>, ) { val backStack: SnapshotStateList<NavKey> = mutableStateListOf(startDestination) fun goTo(destination: NavKey) { backStack.add(destination) } fun handleDeepLink(intent: Intent) { if (intent.data == null && intent.extras == null) return val request = DeepLinkRequest(intent) val matchResult = deepLinkMatchers.firstNotNullOfOrNull { matcher -> matcher.match(request) } ?: return backStack.clear() backStack.addAll(matchResult.backStack) } fun goBack() { backStack.removeLastOrNull() } }
package com.example.nav3recipes.modular.hilt import androidx.navigation3.runtime.NavKey import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent @Module @InstallIn(ActivityRetainedComponent::class) object AppModule { @Provides fun provideStartDestination(): NavKey = ConversationList }