### GET /api/v1/example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/README.md Retrieves a list of example results from the API. ```APIDOC ## GET /api/v1/example ### Description Retrieves a list of example results. ### Method GET ### Endpoint /api/v1/example ### Returns Response> ``` -------------------------------- ### GET /api/v1/example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/endpoints.md Retrieves a list of example data from the remote server. This endpoint does not require authentication and returns a JSON array of example objects, each containing a title and description. ```APIDOC ## GET /api/v1/example ### Description Retrieves a list of example data from the remote server. ### Method GET ### Endpoint `/api/v1/example` ### Parameters #### Query Parameters None. ### Request Example No request body required. ### Response #### Success Response (200 OK) **Content-Type:** `application/json` **Schema:** Array of example objects ```json [ { "title": "Example Title 1", "description": "Example Description 1" }, { "title": "Example Title 2", "description": "Example Description 2" } ] ``` #### Response Body Schema | Field | Type | Required | Description | |---|---|---|---| | title | string | Yes | Example title | | description | string | Yes | Example description | #### Error Response (404 Not Found) **Response:** ```json { "error": "Not Found", "status": 404 } ``` #### Error Response (500 Internal Server Error) **Response:** ```json { "error": "Internal Server Error", "status": 500, "message": "An error occurred while processing your request" } ``` ### Authentication **Required:** No ### Rate Limiting Not specified in API documentation. ``` -------------------------------- ### GET /api/v1/example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/INDEX.txt Retrieves example data from the API. This endpoint is documented in endpoints.md and api-reference-remote.md. ```APIDOC ## GET /api/v1/example ### Description Retrieves example data from the API. ### Method GET ### Endpoint /api/v1/example ### Response #### Success Response (200) - **data** (ExampleModel or Resource) - Description of the data returned. ### Response Example { "example": "response body" } ``` -------------------------------- ### ViewModel for Loading Examples Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/endpoints.md Manages the UI state and triggers the loading of examples from the repository. Uses StateFlow to expose UI state updates. ```kotlin @HiltViewModel class HomeViewModel @Inject constructor( private val repository: ExampleRepository ) : ViewModel() { private val _uiState = MutableStateFlow(HomeScreenState()) val uiState: StateFlow = _uiState.asStateFlow() fun loadExamples() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } try { repository.fetchAndCacheExamples() } finally { _uiState.update { it.copy(isLoading = false) } } } } } ``` -------------------------------- ### Room Database Usage Example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Example of how to obtain the AppDatabase instance and access its DAOs to fetch data. ```kotlin val database: AppDatabase = // from Hilt val dao: ExampleDao = database.getExampleDao() val allData: List = dao.getExampleData() ``` -------------------------------- ### Inject Example Repository Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Injects the ExampleDao into the ExampleRepository. This repository is marked with @Singleton, ensuring a single instance throughout the application. ```kotlin import javax.inject.Inject import javax.inject.Singleton @Singleton class ExampleRepository @Inject constructor( private val exampleDao: ExampleDao ) ``` -------------------------------- ### AppDatabase - getExampleDao() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Abstract method to retrieve the Data Access Object for example entities from the AppDatabase. ```APIDOC ## getExampleDao() ### Description Returns the Data Access Object for example entities. ### Method ```kotlin abstract fun getExampleDao(): ExampleDao ``` ### Return Type `ExampleDao` ### Usage Example ```kotlin val database: AppDatabase = // obtained via dependency injection val dao: ExampleDao = database.getExampleDao() val allData: List = dao.getExampleData() ``` ``` -------------------------------- ### Room Database Builder with Callback Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Example of building a Room database instance and registering a custom callback for lifecycle events. ```kotlin Room.databaseBuilder( application, AppDatabase::class.java, "local_database" ).addCallback(callback).build() ``` -------------------------------- ### Retrieve All Example Entities Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Retrieves all entities from the 'example_table'. Returns an empty list if no records exist. Useful for displaying all stored data. ```kotlin val allEntities: List = exampleDao.getExampleData() allEntities.forEach { println("${entity.id}: ${entity.title}") } ``` -------------------------------- ### Example Response JSON Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/endpoints.md This is the JSON structure for a successful response when retrieving example data. ```json [ { "title": "Example Title 1", "description": "Example Description 1" }, { "title": "Example Title 2", "description": "Example Description 2" } ] ``` -------------------------------- ### getExampleResult() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-remote.md Fetches a list of example data from the remote API. This method retrieves a list of ExampleModel objects from the /api/v1/example endpoint. ```APIDOC ## GET /api/v1/example ### Description Fetches a list of example data from the remote API. This method retrieves a list of ExampleModel objects from the /api/v1/example endpoint. ### Method GET ### Endpoint /api/v1/example ### Parameters None. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **body** (List) - A list of ExampleModel objects on success. #### Response Example ```json [ { "title": "Example 1", "description": "Description 1" }, { "title": "Example 2", "description": "Description 2" } ] ``` ### Data Model Each object in the response array maps to `ExampleModel` with the following properties: | Field | Type | Description | |-------|------|-------------| | title | string | Title of the example | | description | string | Description of the example | ``` -------------------------------- ### getExampleResult() Method Signature Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-remote.md Signature for fetching a list of example data from the remote API. ```kotlin @GET("/api/v1/example") suspend fun getExampleResult(): Response> ``` -------------------------------- ### DetailScreen Navigation Setup in NavGraph Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-screens.md Configures the navigation graph to handle routes with an 'id' argument for the DetailScreen. ```kotlin // In NavGraph composable composable( "${Screen.Detail.route}/{id}", arguments = listOf(navArgument("id") { type = NavType.IntType }) ) { DetailScreen( navController = navController, id = it.arguments?.getInt("id") ?: 0 ) } ``` -------------------------------- ### Usage Example for getExampleResult() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-remote.md Demonstrates how to call the getExampleResult() method and handle the response, including success and error cases. Ensure the AppApi service is injected before use. ```kotlin val apiService: AppApi = // injected via Hilt try { val response = apiService.getExampleResult() if (response.isSuccessful) { val examples: List? = response.body() examples?.forEach { model -> println("Title: ${model.title}, Desc: ${model.description}") } } else { val errorCode = response.code() println("API Error: $errorCode") } } catch (e: Exception) { println("Network error: ${e.message}") } ``` -------------------------------- ### getExampleData() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Retrieves all example entities from the database table. This function queries the 'example_table' and returns a list of all stored ExampleEntity objects. If the table is empty, an empty list is returned. ```APIDOC ## getExampleData() ### Description Retrieves all example entities from the database table. ### Method GET (Conceptual - Room DAO method) ### Endpoint N/A (Room DAO operation) ### Parameters None. ### Return Type **Type:** `List` List of all entities stored in `example_table`. Empty list if no records exist. ### Usage Example ```kotlin val allEntities: List = exampleDao.getExampleData() allEntities.forEach { entity -> println("${entity.id}: ${entity.title}") } ``` ``` -------------------------------- ### Hilt Module for API Client Provision Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md An example of a Hilt module that provides the `AppApi` instance, configured with Retrofit. This is part of the dependency injection setup. ```kotlin @Module @InstallIn(SingletonComponent::class) object ApiModule { @Provides @Singleton fun provideAppApi(retrofit: Retrofit): AppApi = ... } ``` -------------------------------- ### Usage Example in ViewModel Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/endpoints.md Demonstrates how to call the API service from a ViewModel using coroutines and StateFlow. Handles loading states and potential errors. ```kotlin val apiService: AppApi = // from Hilt dependency injection try { val response: Response> = apiService.getExampleResult() if (response.isSuccessful) { val examples: List? = response.body() examples?.forEach { example -> println("Title: ${example.title}") println("Description: ${example.description}") } } else { val errorCode = response.code() println("HTTP Error: $errorCode") } } catch (e: IOException) { println("Network error: ${e.message}") } catch (e: JsonSyntaxException) { println("Invalid JSON response: ${e.message}") } ``` -------------------------------- ### Usage Example for hasInternetConnection() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-utilities.md Demonstrates how to use the NetworkUtil.hasInternetConnection() method to conditionally perform network operations or display an offline message. ```kotlin val context: Context = this if (NetworkUtil.hasInternetConnection(context)) { // Perform network operations viewModel.fetchData() } else { // Show offline message toast("No internet connection") } ``` -------------------------------- ### NavGraph Composable Setup Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md Sets up the main navigation graph for the application using NavHostController. This is typically called within the main activity's setContent block. ```kotlin // In MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface(color = MaterialTheme.colorScheme.background) { val navController = rememberNavController() NavGraph(navController = navController) } } } } ``` -------------------------------- ### Provide Example DAO Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Creates a DAO for database access. This function is not @Singleton, meaning a new instance is created per injection. It is stateless as data persists in the database, making multiple instances safe to create. ```kotlin import javax.inject.Inject import dagger.Module import dagger.Provides @Module object DatabaseModule { @Provides fun provideExampleDao(database: AppDatabase): ExampleDao { return database.exampleDao() } } ``` -------------------------------- ### Abstract DAO Getter Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Abstract method to retrieve the Data Access Object for example entities. ```kotlin abstract fun getExampleDao(): ExampleDao ``` -------------------------------- ### Inject AppApi into Repository Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Example of injecting the AppApi service into a repository for use in type-safe API calls. ```kotlin @Singleton class ExampleRepository @Inject constructor( private val appApi: AppApi ) ``` -------------------------------- ### fromTimestamp() Usage Example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Demonstrates converting a Unix timestamp and a null value to Date objects using the custom type converter. ```kotlin val timestamp: Long = 1704067200000L // 2024-01-01 val date: Date = converter.fromTimestamp(timestamp) val nullDate: Date = converter.fromTimestamp(null) // Current date ``` -------------------------------- ### DetailScreen Composable Usage Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-viewmodels.md Example of how to use DetailViewModel within a Jetpack Compose DetailScreen. The ViewModel is automatically injected by Hilt. ```kotlin import androidx.compose.runtime.Composable import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController @Composable fun DetailScreen( viewModel: DetailViewModel = hiltViewModel(), navController: NavController, id: Int ) { // viewModel is automatically injected by Hilt // id parameter comes from navigation argument } ``` -------------------------------- ### insert() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Inserts a new example entity into the database. If an entity with the same primary key already exists, it will be replaced due to the `OnConflictStrategy.REPLACE` strategy. This is a suspending function. ```APIDOC ## insert() ### Description Inserts a new example entity into the database, replacing if it already exists. ### Method POST (Conceptual - Room DAO method) ### Endpoint N/A (Room DAO operation) ### Parameters #### Request Body - **search** (ExampleEntity?) - Required - The entity to insert. Can be null. ### Return Type **Type:** `Unit` Suspending function, no return value. ### Conflict Resolution Uses `OnConflictStrategy.REPLACE` - if an entity with the same primary key exists, it will be replaced. ### Throws **Type:** Database-related exceptions (e.g., SQLiteException) if database operation fails. ### Usage Example ```kotlin val newEntity = ExampleEntity( title = "New Example", description = "This is new" ) // In coroutine context viewModelScope.launch { exampleDao.insert(newEntity) } ``` ``` -------------------------------- ### Back Navigation and Route Replacement Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md Provides examples for handling back navigation. `popBackStack` removes the current destination, while `navigate` with `popUpTo` can replace the current route with a new one. ```kotlin // Pop back to previous route navController.popBackStack() // Navigate and replace current route navController.navigate(route) { popUpTo(Screen.Main.route) } ``` -------------------------------- ### delete() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Deletes an example entity from the database. The provided entity must have a valid primary key to be removed. This is a suspending function. ```APIDOC ## delete() ### Description Deletes an example entity from the database. ### Method DELETE (Conceptual - Room DAO method) ### Endpoint N/A (Room DAO operation) ### Parameters #### Request Body - **search** (ExampleEntity) - Required - The entity to delete. Must have valid primary key. ### Return Type **Type:** `Unit` Suspending function, no return value. ### Usage Example ```kotlin val entityToDelete = exampleDao.getExampleData().first() viewModelScope.launch { exampleDao.delete(entityToDelete) } ``` ``` -------------------------------- ### ExampleDao Interface Definition Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Defines the Room DAO interface for example data operations, including queries for retrieval and methods for insertion, update, and deletion. ```kotlin @Dao interface ExampleDao { @Query("SELECT * FROM example_table") fun getExampleData(): List @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(search: ExampleEntity?) @Update suspend fun update(search: ExampleEntity) @Delete suspend fun delete(search: ExampleEntity) } ``` -------------------------------- ### update() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Updates an existing example entity in the database. The provided entity must have a valid primary key for the update to be successful. This is a suspending function. ```APIDOC ## update() ### Description Updates an existing example entity in the database. ### Method PUT (Conceptual - Room DAO method) ### Endpoint N/A (Room DAO operation) ### Parameters #### Request Body - **search** (ExampleEntity) - Required - The entity with updated values. Must have valid primary key. ### Return Type **Type:** `Unit` Suspending function, no return value. ### Throws **Type:** Database-related exceptions if the entity does not exist or database operation fails. ### Usage Example ```kotlin val existingEntity = exampleDao.getExampleData().first() val updated = existingEntity.copy(title = "Updated Title") viewModelScope.launch { exampleDao.update(updated) } ``` ``` -------------------------------- ### Performing Local Database Operations with Room Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/README.md Provides examples of common Room database operations: insert, query all, update, and delete. This code should be run within a CoroutineScope, typically `viewModelScope`. ```kotlin // In Repository or ViewModel viewModelScope.launch { // Insert exampleDao.insert(entity) // Query all val allData = exampleDao.getExampleData() // Update exampleDao.update(entity) // Delete exampleDao.delete(entity) } ``` -------------------------------- ### Insert New Example Entity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Inserts a new entity into the database. If an entity with the same primary key exists, it will be replaced. This is a suspending function and should be called within a coroutine scope. ```kotlin val newEntity = ExampleEntity( title = "New Example", description = "This is new" ) // In coroutine context viewModelScope.launch { exampleDao.insert(newEntity) } ``` -------------------------------- ### Delete Example Entity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Deletes an entity from the database. The entity must have a valid primary key. This is a suspending function and requires a coroutine context. ```kotlin val entityToDelete = exampleDao.getExampleData().first() viewModelScope.launch { exampleDao.delete(entityToDelete) } ``` -------------------------------- ### ExampleEntity Usage and Database Insertion Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Creates an ExampleEntity instance and demonstrates how to insert it into the Room database using a DAO. Ensure the DAO is properly configured. ```kotlin val entity = ExampleEntity( id = 1, title = "Local Title", description = "Stored locally" ) // Insert to database via DAO exampleDao.insert(entity) ``` -------------------------------- ### provideExampleDao() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Creates a DAO for database access. This function is responsible for providing an instance of ExampleDao, which is used for interacting with the application's database. ```APIDOC ## provideExampleDao() ### Description Creates a DAO for database access. This function is responsible for providing an instance of ExampleDao, which is used for interacting with the application's database. ### Signature ```kotlin @Provides fun provideExampleDao(database: AppDatabase): ExampleDao ``` ### Parameters #### Path Parameters - **database** (AppDatabase) - Required - Database instance (auto-injected) ### Return Type **Type:** `ExampleDao` Returns the concrete DAO implementation from database. ### Note on Scope - **NOT @Singleton** - New instance per injection - Stateless; actual data persists in database - Safe to create multiple instances ### Injection ```kotlin @Singleton class ExampleRepository @Inject constructor( private val exampleDao: ExampleDao ) ``` **Source:** `app/src/main/java/com/ferhatozcelik/jetpackcomposetemplate/di/DatabaseModule.kt:24` ``` -------------------------------- ### ExampleRepository Class Definition Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-repository.md Defines the ExampleRepository as a singleton using Hilt for dependency injection. It requires AppApi for remote operations and ExampleDao for local data access. ```kotlin import javax.inject.Inject import javax.inject.Singleton @Singleton class ExampleRepository @Inject constructor( private val appApi: AppApi, private val exampleDao: ExampleDao ) ``` -------------------------------- ### ExampleEntity Constructor Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Defines the Room database entity for local storage. Includes an optional ID for primary key and fields for title and description. ```kotlin ExampleEntity( id: Int? = null, title: String?, description: String? ) ``` -------------------------------- ### ViewModel Usage of ExampleRepository Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-repository.md Demonstrates how ExampleRepository is injected into a Hilt-annotated ViewModel. The repository instance is automatically provided by Hilt. ```kotlin @HiltViewModel class MyViewModel @Inject constructor( private val repository: ExampleRepository ) : ViewModel() { // Repository is auto-injected by Hilt } ``` -------------------------------- ### ExampleModel Usage Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Instantiates an ExampleModel object with provided title and description. This is useful for creating mock data or initializing models. ```kotlin val model = ExampleModel( title = "Example Title", description = "Example Description" ) ``` -------------------------------- ### MainScreen Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-screens.md Home/main screen composable showing navigation entry point. ```APIDOC ## MainScreen ### Description Home/main screen composable showing navigation entry point. ### Signature ```kotlin @Composable fun MainScreen( viewModel: HomeViewModel = hiltViewModel(), navController: NavHostController, ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **viewModel** (HomeViewModel) - Optional - Injected home view model - **navController** (NavHostController) - Required - Navigation controller for routing ### Annotations - `@Composable` - Jetpack Compose composable function - `@SuppressLint("UnusedMaterialScaffoldPaddingParameter")` - Suppress lint warning for Scaffold padding ### Return Type `Unit` - Composable that renders to screen. ### Layout Structure ``` Column (fill max size) ├── verticalArrangement: Center ├── horizontalAlignment: CenterHorizontally └── Button └── Text("Go to Detail") ``` ### UI Components | Component | Properties | Action | |-----------|-----------|--------| | Column | fillMaxSize, centered | Container | | Button | onClick | Navigate to DetailScreen with id=123 | | Text | "Go to Detail" | Button label | ### Navigation Clicking the button navigates to: - **Route:** `detail_screen/123` - **Argument:** id = 123 (Int) - **Target:** `DetailScreen` ### Usage Example ```kotlin // In NavGraph composable composable(Screen.Main.route) { MainScreen(navController = navController) } // Or standalone preview @Preview @Composable fun MainScreenPreview() { // Mock navController for preview MainScreen(navController = rememberNavController()) } ``` ### Source `com.ferhatozcelik.jetpackcomposetemplate.ui.home.MainScreen` `app/src/main/java/com/ferhatozcelik/jetpackcomposetemplate/ui/home/MainScreen.kt:16` ``` -------------------------------- ### Define Hilt AppModule Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Defines a Hilt module for application-level dependencies, installing it into the SingletonComponent and providing a singleton application-scoped CoroutineScope. ```kotlin import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @ApplicationScope @Provides @Singleton fun provideApplicationScope(): CoroutineScope { return CoroutineScope(SupervisorJob()) } } ``` -------------------------------- ### toTimestamp() Usage Example Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-database.md Demonstrates converting a Date object and a null value to Long timestamps using the custom type converter. ```kotlin val date = Date() val timestamp: Long = converter.toTimestamp(date) val currentTimestamp: Long = converter.toTimestamp(null) ``` -------------------------------- ### ExampleRepository Constructor Signature Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-repository.md The constructor for ExampleRepository, marked with @Inject for Hilt dependency injection. It takes AppApi and ExampleDao as parameters. ```kotlin @Inject constructor( appApi: AppApi, exampleDao: ExampleDao ) ``` -------------------------------- ### DatabaseModule Definition Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Defines the Hilt module for providing Room database and DAO dependencies. It's installed in the SingletonComponent for app-wide availability. ```kotlin @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDatabase( application: Application, callback: AppDatabase.Callback ): AppDatabase @Provides fun provideExampleDao(database: AppDatabase): ExampleDao } ``` -------------------------------- ### Usage Pattern for Navigating to Detail Screen Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md Demonstrates a common usage pattern within a composable to navigate to the detail screen with a specific ID. ```kotlin object MainScreen { Button(onClick = { navController.navigate(Screen.Detail.route + "/123") }) { Text("Go to Detail") } } ``` -------------------------------- ### ViewModel Data Fetching and Caching Flow Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-repository.md Illustrates a typical data flow within a ViewModel using ExampleRepository. It fetches data from the remote API via appApi, checks for success, converts the response, and inserts it into the local database using exampleDao. ```kotlin // In ViewModel viewModelScope.launch { // Attempt to fetch from remote val remoteResponse = repository.appApi.getExampleResult() if (remoteResponse.isSuccessful) { val models = remoteResponse.body() ?: emptyList() // Convert and cache locally models.forEach { model -> val entity = ExampleEntity( title = model.title, description = model.description ) repository.exampleDao.insert(entity) } } } ``` -------------------------------- ### Gone View Extension Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/module-index.md Extension function to hide a View by setting its visibility to GONE. No specific setup required beyond importing the extension. ```kotlin fun View.gone() {} ``` -------------------------------- ### Architecture Layers Overview Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/00-START-HERE.md Illustrates the layered architecture of the application, from the Presentation Layer down to Dependency Injection. ```text Presentation Layer → MainScreen, DetailScreen, ViewModels ↓ Data Layer → Repository, API, Database ↓ Dependency Injection → Hilt modules (App, Api, Database) ``` -------------------------------- ### Create Retrofit Instance Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Configures and builds a Retrofit instance using the provided OkHttpClient, base URL, and Gson converter. This instance is ready for API communication. ```kotlin Retrofit.Builder() .baseUrl(BASE_URL) // "https://api.ferhatozcelik.com" .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() ``` -------------------------------- ### Update Existing Example Entity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dao.md Updates an existing entity in the database. The entity must have a valid primary key. This is a suspending function and requires a coroutine context. ```kotlin val existingEntity = exampleDao.getExampleData().first() val updated = existingEntity.copy(title = "Updated Title") viewModelScope.launch { exampleDao.update(updated) } ``` -------------------------------- ### ExampleModel JSON Data Structure Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-remote.md Shows the expected JSON structure for the response body, mapping to the ExampleModel class. ```json [ { "title": "Example 1", "description": "Description 1" }, { "title": "Example 2", "description": "Description 2" } ] ``` -------------------------------- ### Typical DetailViewModel Implementation Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-viewmodels.md A typical implementation pattern for DetailViewModel, including state management with MutableStateFlow and data loading logic. ```kotlin import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ferhatozcelik.jetpackcomposetemplate.data.ExampleRepository import com.ferhatozcelik.jetpackcomposetemplate.ui.detail.DetailScreenState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( private val exampleRepository: ExampleRepository ) : ViewModel() { private val _screenState = MutableStateFlow( DetailScreenState() ) val screenState: StateFlow = _screenState.asStateFlow() fun loadDetail(id: Int) { viewModelScope.launch { _screenState.update { it.copy(isLoading = true) } try { val allData = exampleRepository.exampleDao.getExampleData() val detail = allData.find { it.id == id } // Handle detail } finally { _screenState.update { it.copy(isLoading = false) } } } } } ``` -------------------------------- ### MainScreen Usage in NavGraph and Preview Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-screens.md Shows how to integrate MainScreen into a Jetpack Navigation graph and how to create a standalone preview. ```kotlin // In NavGraph composable composable(Screen.Main.route) { MainScreen(navController = navController) } // Or standalone preview @Preview @Composable fun MainScreenPreview() { // Mock navController for preview MainScreen(navController = rememberNavController()) } ``` -------------------------------- ### ViewModel State Management in Kotlin Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Use ViewModels to hold UI state that survives configuration changes. This example shows a HomeViewModel managing HomeScreenState using MutableStateFlow. ```kotlin import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val repository: ExampleRepository ) : ViewModel() { private val _state = MutableStateFlow(HomeScreenState()) val state: StateFlow = _state.asStateFlow() fun loadData() { viewModelScope.launch { ... } } } ``` -------------------------------- ### ExampleEntity Room Database Entity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/types.md A Room database entity for persisting example data. Implements Parcelable for intent passing and is used in database queries and navigation arguments. ```kotlin @Parcelize @Entity(tableName = "example_table") data class ExampleEntity( @PrimaryKey(autoGenerate = true) var id: Int? = null, val title: String?, val description: String? ) : Parcelable ``` -------------------------------- ### Go to URL Context Extension Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/module-index.md Extension function to open a URL in a browser. Requires a Context and the URL as a String. ```kotlin fun Context.goURL(url: String) {} ``` -------------------------------- ### HomeViewModel with StateFlow and CoroutineScope Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-viewmodels.md Illustrates a typical pattern for HomeViewModel, managing screen state using MutableStateFlow and launching coroutines with viewModelScope for asynchronous operations. ```kotlin @HiltViewModel class HomeViewModel @Inject constructor( private val exampleRepository: ExampleRepository ) : ViewModel() { private val _screenState = MutableStateFlow( HomeScreenState() ) val screenState: StateFlow = _screenState.asStateFlow() fun loadData() { viewModelScope.launch { _screenState.update { it.copy(isLoading = true) } try { val response = exampleRepository.appApi.getExampleResult() // Handle response } finally { _screenState.update { it.copy(isLoading = false) } } } } } ``` -------------------------------- ### ExampleEntity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Room database entity for local data persistence. It stores an ID, title, and description. ```APIDOC ## ExampleEntity ### Description Room database entity for local data persistence. ### Constructor ```kotlin ExampleEntity( id: Int? = null, title: String?, description: String? ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | id | Int? | No | null | Auto-generated primary key | | title | String? | Yes | — | The entity title | | description | String? | Yes | — | The entity description | ### Usage Example ```kotlin val entity = ExampleEntity( id = 1, title = "Local Title", description = "Stored locally" ) // Insert to database via DAO exampleDao.insert(entity) ``` ``` -------------------------------- ### HomeViewModel Constructor Injection Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-viewmodels.md Shows the constructor for HomeViewModel, utilizing Hilt's @Inject annotation for dependency injection of ExampleRepository. ```kotlin @Inject constructor(exampleRepository: ExampleRepository) ``` -------------------------------- ### Provide Room Database Instance Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Creates a singleton instance of the Room database. It's configured with a specific name, destructive migration, and a callback for lifecycle hooks. ```kotlin @Provides @Singleton fun provideDatabase( application: Application, callback: AppDatabase.Callback ): AppDatabase ``` -------------------------------- ### AppModule Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md The AppModule is a Hilt module responsible for providing application-level dependencies and managing application scopes. It installs itself into the SingletonComponent, ensuring that its provided dependencies are singletons throughout the application's lifecycle. ```APIDOC ## AppModule ### Description Module providing application-level dependencies and scopes. It is installed into the `SingletonComponent`. ### Annotations - `@Module`: Declares this object as a Hilt module. - `@InstallIn(SingletonComponent::class)`: Specifies that this module's bindings will be installed in the application's singleton component. ### Provides - `provideApplicationScope()`: Provides a singleton `CoroutineScope` qualified with `@ApplicationScope`. ``` -------------------------------- ### Composition State Management in Jetpack Compose Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Manage UI state within composables using `remember` and `collectAsState` to observe ViewModel state changes. This example displays a loading indicator based on the state. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @Composable fun MainScreen(viewModel: HomeViewModel) { val state: HomeScreenState by viewModel.state.collectAsState() Column { if (state.isLoading) { CircularProgressIndicator() } } } ``` -------------------------------- ### Main Screen Navigation Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md Navigates to the main screen. This is typically the entry point of the application. ```kotlin navController.navigate(Screen.Main.route) ``` -------------------------------- ### Usage of AppApi Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Demonstrates how to call API methods and retrieve response bodies using the injected AppApi service. ```kotlin val response = appApi.getExampleResult() val models: List? = response.body() ``` -------------------------------- ### Detail Screen Navigation with Parameter Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md Navigates to the detail screen, passing an ID as a parameter. The ID is appended to the base detail screen route. ```kotlin navController.navigate(Screen.Detail.route + "/123") // Navigate with id=123 ``` -------------------------------- ### ExampleModel Constructor Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Defines the data transfer object for API responses. Use this to create instances representing data fetched from an API. ```kotlin ExampleModel( title: String?, description: String? ) ``` -------------------------------- ### Project Structure Overview Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Illustrates the directory layout of the Jetpack Compose template, highlighting the organization of source code, resources, and build files. ```tree jetpack-compose-template/ ├── app/ │ ├── src/ │ │ ├── main/ │ │ │ ├── java/com/ferhatozcelik/jetpackcomposetemplate/ │ │ │ │ ├── App.kt (Hilt entry point) │ │ │ │ ├── data/ │ │ │ │ │ ├── dao/ (Database access) │ │ │ │ │ ├── entity/ (Room entities) │ │ │ │ │ ├── local/ (Database configuration) │ │ │ │ │ ├── model/ (API models) │ │ │ │ │ ├── remote/ (Retrofit API) │ │ │ │ │ └── repository/ (Data abstraction) │ │ │ │ ├── di/ (Dependency injection) │ │ │ │ ├── navigation/ (Navigation routes) │ │ │ │ ├── ui/ │ │ │ │ │ ├── activitys/ (Entry activity) │ │ │ │ │ ├── home/ (Home screen) │ │ │ │ │ ├── detail/ (Detail screen) │ │ │ │ │ └── theme/ (UI theme) │ │ │ │ └── util/ (Utilities) │ │ │ ├── res/ (Resources) │ │ │ └── AndroidManifest.xml │ │ ├── test/ (Unit tests) │ │ └── androidTest/ (Instrumented tests) │ └── build.gradle ├── gradle/ │ └── libs.versions.toml (Dependency catalog) ├── build.gradle ├── settings.gradle └── README.md ``` -------------------------------- ### Open URL Extension Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-utilities.md Opens a given URL in the device's default browser. Includes basic error handling for cases where no browser is available. ```kotlin fun Context.goURL(url: String) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } catch (e: ActivityNotFoundException) { toast("No browser application found") } catch (e: Exception) { Log.e("goURL", "Error opening URL: $url", e) e.printStackTrace() } } ``` ```kotlin val context: Context = this context.goURL("https://github.com/ferhatozcelik") // Or from Activity goURL("https://www.example.com") ``` -------------------------------- ### Making API Calls with Retrofit Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/README.md Illustrates how to make network requests using Retrofit and handle the response. This snippet assumes `appApi` is an instance of your Retrofit API interface and `ExampleModel` is your data model. ```kotlin // In Repository or ViewModel try { val response = appApi.getExampleResult() if (response.isSuccessful) { val data: List? = response.body() // Use data } } catch (e: Exception) { // Handle error } ``` -------------------------------- ### Context.goURL() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-utilities.md Opens a URL in the device's default browser. ```APIDOC ## Context.goURL() ### Description Opens a URL in the device browser. ### Signature ```kotlin fun Context.goURL(url: String) ``` ### Parameters #### Path Parameters - **url** (String) - Required - Full URL to open (http/https) ### Return Type `Unit` ### Exception Handling - **ActivityNotFoundException:** Shows toast if no browser is available - **General:** Logs exception with `printStackTrace()` ### Usage Example ```kotlin val context: Context = this context.goURL("https://github.com/ferhatozcelik") // Or from Activity goURL("https://www.example.com") ``` ``` -------------------------------- ### Apply MyApplicationTheme in MainActivity Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-theme.md Applies the MyApplicationTheme to the entire application content. This is typically done in the MainActivity's setContent block. ```kotlin // In MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface(color = MaterialTheme.colorScheme.background) { // App content here } } } } ``` -------------------------------- ### Repository Implementation for Fetching and Caching Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/endpoints.md Handles fetching data from the API and caching it locally using Room. Includes error handling for network and data conversion issues. ```kotlin @Singleton class ExampleRepository @Inject constructor( private val appApi: AppApi, private val exampleDao: ExampleDao ) { suspend fun fetchAndCacheExamples() { try { val response = appApi.getExampleResult() if (response.isSuccessful) { val models = response.body() ?: emptyList() // Convert and cache locally models.forEach { model -> val entity = ExampleEntity( title = model.title, description = model.description ) exampleDao.insert(entity) } } } catch (e: Exception) { // Handle error } } } ``` -------------------------------- ### View.show() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-utilities.md Makes a View visible by setting its visibility to View.VISIBLE. ```APIDOC ## View.show() ### Description Makes a View visible. ### Signature ```kotlin fun View.show() ``` ### Return Type `Unit` ### Implementation Sets `View.visibility` to `View.VISIBLE`. ### Usage Example ```kotlin val myView: View = findViewById(R.id.my_view) myView.show() // View is now visible ``` ``` -------------------------------- ### Repository Implementation for Data Abstraction Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Shows the structure of the Repository class, which acts as a single source of truth by abstracting remote API calls and local database access. ```kotlin @Singleton class ExampleRepository @Inject constructor( private val appApi: AppApi, private val exampleDao: ExampleDao ) ``` -------------------------------- ### Type-Safe Navigation to DetailScreen Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-screens.md Demonstrates how to navigate to the DetailScreen with a specific item ID. ```kotlin navController.navigate(Screen.Detail.route + "/123") ``` -------------------------------- ### Create OkHttpClient with Logging Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Creates an OkHttpClient instance, injecting the previously configured logging interceptor. This client is used internally by Retrofit. ```kotlin val client: OkHttpClient = // from Hilt // Used internally by Retrofit ``` -------------------------------- ### ViewModel and Composable Integration (MVVM) Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Demonstrates how a ViewModel is integrated with a Composable screen using Hilt. The Composable observes the ViewModel's state for UI updates. ```kotlin // ViewModel @HiltViewModel class HomeViewModel @Inject constructor( private val repository: ExampleRepository ) : ViewModel() // Composable observes ViewModel state @Composable fun MainScreen(viewModel: HomeViewModel = hiltViewModel()) { // Uses viewModel state } ``` -------------------------------- ### Apply Theme to Specific Sections Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-theme.md Demonstrates how to apply a specific theme (e.g., dark theme) to a particular composable section of the UI. This allows for localized theme overrides. ```kotlin // Apply theme to specific sections @Composable fun MyScreen() { MyApplicationTheme(darkTheme = true) { // Force dark theme for this section } } ``` -------------------------------- ### Show View Extension Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-utilities.md Makes a View visible. Call this when you need to display an element that was previously hidden. ```kotlin fun View.show() { visibility = View.VISIBLE } ``` ```kotlin val myView: View = findViewById(R.id.my_view) myView.show() // View is now visible ``` -------------------------------- ### Room Database Configuration Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Configures the Room database builder with the application context, database name, destructive migration strategy, and a custom callback. ```kotlin Room.databaseBuilder(application, AppDatabase::class.java, "local_database") .fallbackToDestructiveMigration() .addCallback(callback) .build() ``` -------------------------------- ### provideApplicationScope() Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-dependency-injection.md Factory function to create and provide a singleton `CoroutineScope` that is qualified with `@ApplicationScope`. This scope is designed for long-lived operations that should persist for the entire duration of the application. ```APIDOC ## provideApplicationScope() ### Description Creates a singleton application-scoped `CoroutineScope` for long-lived operations. ### Signature ```kotlin @ApplicationScope @Provides @Singleton fun provideApplicationScope(): CoroutineScope ``` ### Return Type **Type:** `CoroutineScope` A `CoroutineScope` configured with a `SupervisorJob` for resilient background tasks and the default dispatcher, tied to the application's lifetime. ### Properties - **Job Type:** `SupervisorJob` - Ensures that failures in child coroutines do not cancel sibling coroutines. - **Dispatcher:** `Default` - Uses the default dispatcher for coroutine execution. - **Lifetime:** `Application` - The scope exists for the entire duration of the application. ### Usage Example ```kotlin // Injected in database callback class AppDatabase.Callback @Inject constructor( @ApplicationScope private val applicationScope: CoroutineScope ) : RoomDatabase.Callback() // Or in ViewModel for long-lived operations class MyViewModel @Inject constructor( @ApplicationScope private val appScope: CoroutineScope ) : ViewModel() ``` ### When to Use - Long-lived operations spanning multiple screens. - Background tasks not tied to UI lifecycle. - Database initialization and migrations. - Analytics and logging. ### When NOT to Use - UI operations (use `viewModelScope` instead). - Screen lifecycle operations. - User-initiated tasks that should cancel on screen exit. ### Source `com.ferhatozcelik.jetpackcomposetemplate.di.AppModule` `app/src/main/java/com/ferhatozcelik/jetpackcomposetemplate/di/AppModule.kt:19` ``` -------------------------------- ### MainScreen Button to Navigate to Detail Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-navigation.md A button within the MainScreen composable that triggers navigation to the DetailScreen, passing an ID. ```kotlin // In MainScreen Button(onClick = { navController.navigate(Screen.Detail.route + "/123") }) { Text("Navigate to Detail") } ``` -------------------------------- ### Room Type Converters for Database Persistence Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/architecture-overview.md Illustrates how to implement custom type converters for Room Database to handle complex data types like `Date` that are not directly supported. ```kotlin class Converters { @TypeConverter fun fromTimestamp(value: Long?): Date = ... @TypeConverter fun toTimestamp(value: Date?): Long = ... } ``` -------------------------------- ### Usage of bodyLarge Text Style Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-theme.md Demonstrates how to apply the `bodyLarge` typography style to a `Text` composable. It also shows the implicit usage where `Text` defaults to `bodyLarge`. ```kotlin @Composable fun MyText() { Text( text = "Body Large Text", style = MaterialTheme.typography.bodyLarge ) } // Or implicit via Text defaults Text("Body Large Text") // Uses bodyLarge by default ``` -------------------------------- ### ExampleModel Source: https://github.com/ferhatozcelik/jetpack-compose-template/blob/master/_autodocs/api-reference-data-models.md Data transfer object for serializing and deserializing API responses. It includes properties for title and description. ```APIDOC ## ExampleModel ### Description Data transfer object for serializing and deserializing API responses. ### Constructor ```kotlin ExampleModel( title: String?, description: String? ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | title | String? | Yes | — | The title property from API response | | description | String? | Yes | — | The description property from API response | ### Usage Example ```kotlin val model = ExampleModel( title = "Example Title", description = "Example Description" ) ``` ```