मॉड्यूलर नेविगेशन रेसिपी (Hilt)

इस रेसिपी में, डिपेंडेंसी इंजेक्शन के लिए, Navigation 3 और Dagger/Hilt का इस्तेमाल करके, मल्टी-मॉड्यूल ऐप्लिकेशन को स्ट्रक्चर करने का तरीका बताया गया है. इसका मकसद, डीकपल्ड आर्किटेक्चर बनाना है. इसमें नेविगेशन को अलग-अलग फ़ीचर मॉड्यूल में तय और लागू किया जाता है.

यह कैसे काम करता है

ऐप्लिकेशन को कई मॉड्यूल में बांटा गया है:

  • app मॉड्यूल: यह ऐप्लिकेशन का मुख्य मॉड्यूल है. यह HiltDeepLinkActivity (यह एंट्री पॉइंट, सामान्य और डीप लिंक इंटेंट लॉन्च करने का तरीका दिखाता है), HiltModularActivity (यह NavDisplay को होस्ट करता है और डीप लिंक इंटेंट को Navigator.handleDeepLink(intent) पर डेलिगेट करता है), स्टार्ट डेस्टिनेशन बाइंडिंग उपलब्ध कराता है. साथ ही, फ़ाइनल entryProvider बनाता है.

  • common मॉड्यूल: इस मॉड्यूल में, मुख्य नेविगेशन लॉजिक शामिल होता है. जैसे:

    • Navigator क्लास, जो बैक स्टैक को मैनेज करती है, आने वाले डीप लिंक इंटेंट को रिज़ॉल्व करती है, और handleDeepLink(intent) के ज़रिए सिंथेटिक बैक स्टैक बनाती है.
    • startDestination: NavKey, जिसका इस्तेमाल बैक स्टैक को शुरू करने के लिए किया जाता है.
    • EntryProviderInstaller टाइप. यह एक ऐसा फ़ंक्शन है जिसका इस्तेमाल, फ़ीचर मॉड्यूल, ऐप्लिकेशन के entryProvider में अपने नेविगेशन एंट्री जोड़ने के लिए करते हैं.
    • BackStackMatcher<*, NavKey>, जिसका इस्तेमाल फ़ीचर मॉड्यूल, सिंथेटिक बैक स्टैक के साथ अपने डीप लिंक मैच करने वाले टूल जोड़ने के लिए करते हैं.
  • फ़ीचर मॉड्यूल (उदाहरण के लिए, conversation, profile): हर फ़ीचर को दो सब-मॉड्यूल में बांटा गया है:

    • api मॉड्यूल: यह फ़ीचर के लिए, सार्वजनिक एपीआई तय करता है. इसमें इसके नेविगेशन रूट और डीप लिंक यूआरआई पैटर्न शामिल होते हैं. इससे अन्य मॉड्यूल, इस फ़ीचर पर नेविगेट कर पाते हैं. इसके लिए, उन्हें इसके लागू करने से जुड़ी जानकारी की ज़रूरत नहीं होती.
    • impl मॉड्यूल: यह फ़ीचर को लागू करने की सुविधा देता है. इसमें इसके कंपोज़ेबल, एक EntryProviderInstaller शामिल होता है, जो फ़ीचर के रूट को उसके कंपोज़ेबल पर मैप करता है. साथ ही, .withBackStack के साथ कॉन्फ़िगर किया गया BackStackMatcher<*, NavKey> शामिल होता है, ताकि सही क्रम वाला बैक स्टैक बनाया जा सके. जैसे, [ConversationList, ConversationDetail(id)]. इन दोनों को 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.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
}