Android Kotlin Multiplatform Samples

repository·main·Indexed 23 days ago

https://github.com/android/kotlin-multiplatform-samples

A collection of sample applications demonstrating Kotlin Multiplatform (KMP) development patterns. The Fruitties sample app showcases shared logic for data persistence, networking, and state management using KMP-compatible Jetpack libraries including ViewModel, Room, and DataStore, as well as Ktor for network requests.

Tokens
2.6K
Snippets
4
Records
23
Agent score
79%

What's inside android-kotlin-multiplatform-samples

  1. Explore the Fruitties sample app

    main

    Fruitties is a sample application designed to demonstrate how to build a Kotlin Multiplatform app using modern libraries for data fetching, storage, and UI state management. It specifically showcases the integration of:

    • Kotlin Multiplatform ViewModel: For managing UI state across platforms.
    • Room: For local database persistence.
    • DataStore: For storing key-value pairs and preferences.
    • Ktor: For making network requests to fetch data.
  2. Setup the Fruitties development environment

    main

    To develop with Fruitties, it is highly recommended to install the Kotlin Multiplatform Plugin in Android Studio. This plugin provides:

    • New project wizard: For creating new multiplatform projects.
    • Preflight checks: To ensure your environment is correctly configured.
    • Run configurations: To run, debug, and test both iOS and Android applications directly from Android Studio.
    • Basic Swift support: Includes cross-language debugging, navigation, and quick documentation within the IDE.
  3. Initialize and use AppContainer for dependency injection

    main

    The AppContainer class serves as the central dependency injection container for the Fruitties application. It manages the lifecycle and instantiation of core components like the DataRepository and various ViewModel factories.

    To use it, you must provide an implementation of the Factory interface (which handles platform-specific creation of the Room database and DataStore) during initialization. The container uses lazy initialization for the dataRepository to ensure it is only created when first accessed.

  4. Use DataRepository for data access in Fruitties

    main
    The DataRepository class provides a unified interface for accessing Fruitties data, managing a local database (AppDatabase), a network API (FruittieApi), and a cart state (CartDataStore). It handles the synchronization between network data and local storage, and provides reactive Flow streams for UI updates.
  5. Retrieve and refresh Fruittie data

    main

    The DataRepository manages the lifecycle of the Fruitties catalog by combining local database access with network fetching.

    • getData(): Flow<List<Fruittie>>: Returns a Flow of all available Fruittie objects. If the local database is empty, it automatically triggers a refreshData() call in the background.
    • loadData(): Flow<List<Fruittie>>: Returns a Flow directly from the local database without checking if a refresh is needed.
    • getFruittie(id: Long): Fruittie?: A suspend function to fetch a single Fruittie by its ID from the local database.
    • refreshData(): A suspend function that fetches the latest data from the FruittieApi and updates the local database.
  6. Use MainViewModel to manage Fruitties home screen state

    main

    The MainViewModel is responsible for managing the UI state and business logic for the home screen in the Fruitties application. It consumes a DataRepository to provide a reactive homeUiState and exposes methods to interact with the shopping cart.

    Key Features:

    • homeUiState: A StateFlow<HomeUiState> that combines the list of available Fruittie objects with the current total count of items in the cart. It uses SharingStarted.WhileSubscribed(5000) to manage resource usage, keeping the flow active for 5 seconds after the last subscriber disconnects.
    • addItemToCart(fruittie: Fruittie): A function to add a specific Fruittie to the shopping cart via the repository.
    • HomeUiState: A data class representing the UI state, containing:
      • fruitties: A List<Fruittie> of available items.
      • cartItemCount: An Int representing the total number of items in the cart.
  7. Fetch Fruittie data with FruittieApi

    main

    The FruittieApi interface provides a way to fetch Fruittie data from a remote source. The primary method is getData(pageNumber: Int), which returns a FruittiesResponse.

    By default, pageNumber is set to 0. If a network error occurs that is not a CancellationException, the implementation returns an empty FruittiesResponse containing an empty list and zeroed metadata.