मॉड्यूलर नेविगेशन रेसिपी (Koin)
इस रेसिपी में, डिपेंडेंसी इंजेक्शन के लिए Navigation 3 और Koin का इस्तेमाल करके, मल्टी-मॉड्यूल ऐप्लिकेशन को स्ट्रक्चर करने का तरीका बताया गया है. इसका मकसद एक डिकपल्ड आर्किटेक्चर बनाना है, जिसमें नेविगेशन को अलग-अलग फ़ीचर मॉड्यूल में तय और लागू किया जाता है. यह koin-compose-navigation3 आर्टफ़ैक्ट पर निर्भर करता है.
यह कैसे काम करता है
ऐप्लिकेशन को कई Android मॉड्यूल में बांटा गया है:
-
appमॉड्यूल: यह मुख्य ऐप्लिकेशन मॉड्यूल होता है. यहKoinDeepLinkActivity(एक एंट्री पॉइंट है, जो सामान्य और डीप लिंक इंटेंट लॉन्च करने की सुविधा देता है),KoinModularActivity(यहNavDisplayको होस्ट करता है और डीप लिंक इंटेंट कोNavigator.handleDeepLink(intent)को सौंपता है), और एक सामान्यNavigatorको शुरू करता है (getAll()के ज़रिए सभी रजिस्टर किए गएBackStackMatcher<*, NavKey>को हल करता है). -
commonमॉड्यूल: इस मॉड्यूल में, ऐप्लिकेशन मॉड्यूल और फ़ीचर मॉड्यूल, दोनों के लिए इस्तेमाल किया जाने वाला मुख्य नेविगेशन लॉजिक शामिल होता है. इसमें ये चीज़ें शामिल हैं:Navigatorक्लास, जो पिछली गतिविधियों को मैनेज करती है, आने वाले डीप लिंक इंटेंट को रिज़ॉल्व करती है, औरhandleDeepLink(intent)के ज़रिए सिंथेटिक पिछली गतिविधियां बनाती है.startDestination: NavKey, जिसका इस्तेमाल पिछली गतिविधियों को शुरू करने के लिए किया जाता है.BackStackMatcher<*, NavKey>, जिसका इस्तेमाल फ़ीचर मॉड्यूल, सिंथेटिक पिछली गतिविधियों के साथ डीप लिंक मैच करने वाले टूल को जोड़ने के लिए करते हैं.
-
फ़ीचर मॉड्यूल (जैसे,
conversation,profile): हर सुविधा को दो सब-मॉड्यूल में बांटा गया है:apiमॉड्यूल: यह सुविधा के लिए सार्वजनिक एपीआई तय करता है. इसमें इसके नेविगेशन रूट और डीप लिंक यूआरआई पैटर्न शामिल हैं. इससे अन्य मॉड्यूल, इस सुविधा पर नेविगेट कर सकते हैं. इसके लिए, उन्हें इस सुविधा को लागू करने से जुड़ी जानकारी की ज़रूरत नहीं होती.implमॉड्यूल: इसमें सुविधा को लागू करने का तरीका बताया गया है. इसमें कंपोज़ेबल और KoinModuleशामिल हैं. Koin मॉड्यूल,navigationडीएसएल का इस्तेमाल करके, एंट्री प्रोवाइडर इंस्टॉलर तय करता है. साथ ही,single<BackStackMatcher<*, NavKey>>(named<...>())को.withBackStackके साथ कॉन्फ़िगर करता है, ताकि सही क्रम में पिछली गतिविधियां (जैसे,[ConversationList, ConversationDetail(id)]) सेट की जा सकें.
इस मॉड्यूलर तरीके से, अलग-अलग समस्याओं को साफ़ तौर पर अलग किया जा सकता है. इससे कोड बेस को ज़्यादा बढ़ाया जा सकता है और उसका रखरखाव आसान हो जाता है. हर सुविधा, अपने नेविगेशन लॉजिक के लिए ज़िम्मेदार होती है. साथ ही, app मॉड्यूल सिर्फ़ इन हिस्सों को एक साथ जोड़ता है.
package com.example.nav3recipes.modular.koin 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 kotlinx.serialization.Serializable import org.koin.androidx.scope.dsl.activityRetainedScope import org.koin.core.annotation.KoinExperimentalAPI import org.koin.core.qualifier.named import org.koin.dsl.module import org.koin.dsl.navigation3.navigation // API @Serializable object Profile : NavKey const val PROFILE_URI = "https://www.nav3recipes.com/profile" // IMPL @OptIn(KoinExperimentalAPI::class) val profileModule = module { activityRetainedScope { navigation<Profile> { ProfileScreen() } } single<BackStackMatcher<*, NavKey>>(named<Profile>()) { 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.koin 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 kotlinx.serialization.Serializable import org.koin.androidx.scope.dsl.activityRetainedScope import org.koin.core.annotation.KoinExperimentalAPI import org.koin.core.qualifier.named import org.koin.dsl.module import org.koin.dsl.navigation3.navigation // 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 @OptIn(KoinExperimentalAPI::class) val conversationModule = module { activityRetainedScope { navigation<ConversationList> { ConversationListScreen( onConversationClicked = { conversationDetail -> get<Navigator>().goTo(conversationDetail) } ) } navigation<ConversationDetail> { key -> ConversationDetailScreen(key) { get<Navigator>().goTo(Profile) } } } single<BackStackMatcher<*, NavKey>>(named<ConversationDetail>()) { 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.koin import android.content.Intent import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.deeplink.BackStackMatcher import androidx.navigation3.runtime.deeplink.DeepLinkRequest import androidx.navigation3.runtime.deeplink.invoke class Navigator( startDestination: NavKey, private val deepLinkMatchers: List<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.koin import org.koin.androidx.scope.dsl.activityRetainedScope import org.koin.dsl.module val appModule = module { includes(profileModule, conversationModule) activityRetainedScope { scoped { Navigator( startDestination = ConversationList, deepLinkMatchers = getAll(), ) } } }
package com.example.nav3recipes.modular.koin 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.ui.NavDisplay import com.example.nav3recipes.ui.setEdgeToEdgeConfig import org.koin.android.ext.android.inject import org.koin.android.scope.AndroidScopeComponent import org.koin.androidx.compose.navigation3.getEntryProvider import org.koin.androidx.scope.activityRetainedScope import org.koin.core.Koin import org.koin.core.annotation.KoinExperimentalAPI import org.koin.core.component.KoinComponent import org.koin.core.scope.Scope import org.koin.dsl.koinApplication /** * This recipe demonstrates how to use a modular approach with Navigation 3, * where different parts of the application are defined in separate modules and injected * into the main app using Koin. * * Features (Conversation and Profile) are split into two modules: * - api: defines the public facing routes for this feature * - impl: defines the entryProviders for this feature, these are injected into the app's main activity * The common module defines: * - a common navigator class that exposes a back stack and methods to modify that back stack * - a type that should be used by feature modules to inject entryProviders into the app's main activity * The app module creates the navigator by supplying a start destination and provides this navigator * to the rest of the app module (i.e. MainActivity) and the feature modules. */ @OptIn(KoinExperimentalAPI::class) class KoinModularActivity : ComponentActivity(), AndroidScopeComponent, KoinComponent { // Local Koin Context Instance companion object { private val localKoin = koinApplication { modules(appModule) }.koin } // Override default Koin context to use the local one override fun getKoin(): Koin = localKoin override val scope : Scope by activityRetainedScope() val navigator: Navigator by inject() 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 = getEntryProvider() ) } } } }