<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by zerg 1111 on Medium]]></title>
        <description><![CDATA[Stories by zerg 1111 on Medium]]></description>
        <link>https://medium.com/@b9915034?source=rss-fc8bc3133fb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ow5Sf1sco84cp9vF</url>
            <title>Stories by zerg 1111 on Medium</title>
            <link>https://medium.com/@b9915034?source=rss-fc8bc3133fb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:13:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b9915034/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Support Pagination with SQLite in Android: Working with Room and Paging 3]]></title>
            <link>https://medium.com/@b9915034/how-to-support-pagination-with-sqlite-in-android-working-with-room-and-paging-3-5fba726d4e05?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fba726d4e05</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[paging3]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Fri, 15 May 2026 06:38:42 GMT</pubDate>
            <atom:updated>2026-05-28T15:41:06.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7myPhCGz6N7lra3boZpDFA.png" /><figcaption>Pagination Illustration</figcaption></figure><p>This article explains how to support pagination with Paging 3 and Room database. Note: Edited in 2026/5/18.</p><h3>Introduction</h3><blockquote>How to automatically fetch more data when a user scrolls to the end of a list?</blockquote><p>Pagination is a common practice for displaying a large dataset in a list. While the Room database provides built-in pagination support for your queries, integrating it with a remote data source requires additional setup.</p><h3>Overview</h3><h4>Pagination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7myPhCGz6N7lra3boZpDFA.png" /><figcaption>Pagination Illustration</figcaption></figure><p>Pagination is a mechanism that allows you to gradually load a large dataset to be displayed in pages:</p><ul><li>In mobile settings, a device often only has a small screen which can only display limited data. It is a waste to load the entire dataset because only a minimal fraction of it will be accessed.</li><li>It is more efficient to lazy-load data in pages to save bandwidth on unused items. However, this requires a mechanism to track the user’s current position, and load new pages accordingly.</li><li>The Room database can generate a PagingSource implementation based on your query. This allows us to focus entirely on fetching and saving remote data.</li><li>For this task, there are three load types to be handled in RemoteMediator: LoadType.REFRESH, LoadType.APPEND, and LoadType.PREPEND. The library monitors the local data state, and the user’s current scroll position to determine which to trigger.</li></ul><blockquote>To support pagination with Paging 3 and Room, we need to implement a RemoteMediator to handle LoadType.REFRESH, LoadType.APPEND, and LoadType.PREPEND unless the data only originates from local sources.</blockquote><h4>Load Type Refresh</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jIt_fUrG7PTcZ8JNuUuhFQ.png" /><figcaption>Refreshing the Loaded Data</figcaption></figure><p>LoadType.REFRESH serves as a reset signal for initialization:</p><ul><li>When LoadType.REFRESH is triggered, the current data should be replaced with fresh data from the network.</li><li>This fresh data should be fetched using either the remote key from the latest bound item or the index of the first page depending on whether we are restoring the scroll position.</li><li>For example, if the user has just launched the list, RemoteMediator should clear the old data cached from the previous session, and fetch the first page.</li><li>LoadType.REFRESH can be triggered by initializations or user requests. It is possible to skip LoadType.REFRESH from initialization by overriding initialize() in RemoteMediator to return InitializeAction.SKIP_INITIAL_REFRESH.</li><li>In initialize(), you can implement an expiration logic by checking the previous update time to decide whether to skip LoadType.REFRESH or not.</li></ul><blockquote>LoadType.REFRESH is triggered when data needs to be replaced. This load type can be skipped during initialization if up-to-date data is not strictly required.</blockquote><h4>Load Type Append</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*wWNbs60v6pZY49qtz32W5A.png" /><figcaption>Appending the Next Page to Loaded Data</figcaption></figure><p>LoadType.APPEND is used to trigger the next page load:</p><ul><li>When any item within the range of prefetchDistance to the last index is bound, the next page should be loaded using the remote key from the last item of loaded data.</li><li>Assuming the user has an initial load size of three pages and prefetchDistance<em> </em>is one page size<em>, </em>LoadType.APPEND is triggered when the user scrolls into the third page.</li><li>Although there are no strict constraints on prefetchDistance<em>, </em>it is recommended to set it to one-third of the initial load size. This and a proper page size minimize the risk of LoadType.APPEND being triggered immediately following LoadType.REFRESH.</li></ul><blockquote>LoadType.APPEND is triggered when the next page needs to be loaded. Properly configuring the page size and prefetchDistance prevents multiple data loads from being triggered simultaneously.</blockquote><h4>Load Type Prepend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*eL3eLyprMEn4LP-hbT0ZzQ.png" /><figcaption>Prepending the Previous Page to Loaded Data</figcaption></figure><p>LoadType.PREPEND is used to trigger the previous page load:</p><ul><li>If any item in the range of the first index to prefetchDistance is bound, the previous page should be loaded using the remote key from the first item of loaded data.</li><li>This load type is used when the initial anchor position is set mid-list (such as during UI state restoration) to fetch preceding pages to fill the list above the current scroll position.</li><li>By forcing LoadType.REFRESH to always fetch the first page, we can omit LoadType.PREPEND by skipping data fetching. Because the first page has no previous page, subsequent pages are always appended after it.</li><li>It is still recommended to properly implement LoadType.REFRESH and LoadType.PREPEND. Otherwise, the paging list will be unable to restore its scroll position when the UI state is restored.</li></ul><blockquote>LoadType.PREPEND is triggered when the previous page needs to be loaded. Unlike LoadType.APPEND, remote data fetching for prepend is unnecessary if LoadType.REFRESH always initializes the list from the start.</blockquote><h4>Remote Keys</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*dAQVXhqgNGcSCiwoF3q6ZQ.png" /><figcaption>Illustration of an Item and Its Remote Keys</figcaption></figure><p>Remote keys are the page indices used in data-fetching API calls:</p><ul><li>RemoteMediator provides the indices of UI-bound items to fetch new pages. For every item inserted into the database, we must store the previous and next page indices associated with that item.</li><li>For LoadType.REFRESH, the most recently bound item is used to retrieve the current page index.</li><li>For LoadType.APPEND, the last item of loaded data is used to retrieve the next page index.</li><li>For LoadType.PREPEND, the first item of loaded data is used to retrieve the previous page index.</li><li>Since this mapping is not provided by default, a dedicated table is required to store this information.</li></ul><blockquote>Mapping item indices to page indices is required for fetching new pages, and we must provide the implementation ourselves.</blockquote><h4>Remote Order</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ciRl20_pfZdLnW4M1iZuag.png" /><figcaption>Illustration of Mapping the Item Sequence from the Remote Dataset</figcaption></figure><p>Remote order refers to the sequence of items as returned by the API response:</p><ul><li>Since we are generating the PagingSource from a SQL statement, we must ensure the local query returns items in the same sequence as the API response.</li><li>Storing the order of items in a dedicated table ensures they are sorted correctly during paged queries.</li><li>Failing to do so can result in a disruptive UX as currently visible items may shift positions when new data is inserted into the middle of the list.</li></ul><blockquote>We must keep track of the item sequence returned by the API to ensure that LoadType.APPEND and LoadType.PREPEND work as expected.</blockquote><h4>Paging Source</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*3OahZlyIY-HDQIHbw4nYQQ.png" /><figcaption>A Simplified Relationship between the Database, Paging Source, and UI</figcaption></figure><p>A PagingSource is an object responsible for retrieving data from its data source in a paged fashion:</p><ul><li>A simple SELECT query is sufficient for Room to generate the PagingSource. To ensure the page order matches the API response, we must use an ORDER BY clause using the remote order previously saved.</li><li>Room currently only supports returning LimitOffsetPagingSource which relies on an integer offset to load pages. Therefore, the PagingSource key type must be an integer.</li><li>Since a PagingSource is invalidated whenever the table is updated, all information related to a new page must be inserted within a single transaction.</li></ul><blockquote>With Room generating PagingSource, we only need to write the SQL statement to retrieve data. The remote keys, remote order, and items must be inserted within a single transaction to avoid multiple invalidations.</blockquote><h3>Implementation Details</h3><h4>Remote Data</h4><pre>@Entity(primaryKeys = [Column.PHOTO_ID])<br>data class PhotoEntity(<br>    @ColumnInfo(name = Column.AUTHOR_ID) val authorId: String,<br>    @ColumnInfo(name = Column.AUTHOR_NAME) val authorName: String,<br>    @ColumnInfo(name = Column.IMAGE_URL) val imageUrl: String,<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.PLANT_NAME) val plantName: String<br>)</pre><ul><li>The items from the API response needs to be saved to generate a PagingSource.</li><li>This table serves as the parent entity. Its primary key will be used as a foreign key by other tables storing pagination metadata.</li></ul><h4>Remote Keys</h4><pre>@Entity(<br>    primaryKeys = [Column.PHOTO_ID],<br>    foreignKeys = [ForeignKey(<br>        childColumns = [Column.PHOTO_ID],<br>        entity = PhotoEntity::class,<br>        onDelete = ForeignKey.CASCADE,<br>        parentColumns = [Column.PHOTO_ID]<br>    )]<br>)<br>data class PhotoRemoteKeysEntity(<br>    @ColumnInfo(name = Column.NEXT_KEY) val nextKey: Int?,<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.PREVIOUS_KEY) val previousKey: Int?<br>)</pre><ul><li>This entity stores the next and previous page keys relative to a specific item ID.</li><li>Since these keys are useless without their corresponding data, we use ForeignKey.CASCADE to automatically delete the remote keys whenever its parent entity is removed.</li></ul><h4>Remote Order</h4><pre>@Entity(<br>    primaryKeys = [Column.PHOTO_ID],<br>    foreignKeys = [ForeignKey(<br>        childColumns = [Column.PHOTO_ID],<br>        entity = PhotoEntity::class,<br>        onDelete = ForeignKey.CASCADE,<br>        parentColumns = [Column.PHOTO_ID]<br>    )]<br>)<br>data class PhotoRemoteOrderEntity(<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.REMOTE_ORDER) val remoteOrder: Int<br>)</pre><ul><li>This table stores the order of items as returned by the API to allow the PagingSource to retrieve them in the correct sequence.</li><li>Like the remote keys, these records are dependent on the parent data. A remote order entity should be deleted whenever its parent entity is missing.</li></ul><h4>Database View</h4><pre>@DatabaseView(<br>    &quot;SELECT &quot; +<br>            &quot;PhotoEntity.${Column.AUTHOR_ID} AS ${Column.AUTHOR_ID}, &quot; +<br>            &quot;PhotoEntity.${Column.AUTHOR_NAME} AS ${Column.AUTHOR_NAME}, &quot; +<br>            &quot;PhotoEntity.${Column.IMAGE_URL} AS ${Column.IMAGE_URL}, &quot; +<br>            &quot;PhotoEntity.${Column.PHOTO_ID} AS ${Column.PHOTO_ID}, &quot; +<br>            &quot;PhotoEntity.${Column.PLANT_NAME} AS ${Column.PLANT_NAME}, &quot; +<br>            &quot;PhotoRemoteOrderEntity.${Column.REMOTE_ORDER} AS ${Column.REMOTE_ORDER} &quot; +<br>            &quot;FROM PhotoEntity &quot; +<br>            &quot;LEFT JOIN PhotoRemoteOrderEntity ON PhotoRemoteOrderEntity.${Column.PHOTO_ID} = PhotoEntity.${Column.PHOTO_ID}&quot;<br>)<br>data class PhotoItemView(<br>    @ColumnInfo(name = Column.AUTHOR_ID) val authorId: String,<br>    @ColumnInfo(name = Column.AUTHOR_NAME) val authorName: String,<br>    @ColumnInfo(name = Column.IMAGE_URL) val imageUrl: String,<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.PLANT_NAME) val plantName: String,<br>    @ColumnInfo(name = Column.REMOTE_ORDER) val remoteOrder: Int?<br>)</pre><ul><li>The database view lets us query items along with their remote order information. It allows us to use an ORDER BY clause on the remote order to ensure the UI matches the API sequence.</li></ul><h4>Data Access Objects</h4><pre>@Dao<br>interface PhotoDao {<br>    @Query(&quot;DELETE FROM PhotoEntity&quot;)<br>    suspend fun clear()<br><br>    @Query(&quot;SELECT * FROM PhotoRemoteKeysEntity WHERE :photoId = ${Column.PHOTO_ID}&quot;)<br>    suspend fun getRemoteKeys(photoId: String): PhotoRemoteKeysEntity?<br><br>    @Upsert<br>    suspend fun upsertPhoto(entities: List&lt;PhotoEntity&gt;)<br><br>    @Upsert<br>    suspend fun upsertRemoteKeys(entities: List&lt;PhotoRemoteKeysEntity&gt;)<br><br>    @Upsert<br>    suspend fun upsertRemoteOrder(entities: List&lt;PhotoRemoteOrderEntity&gt;)<br><br>    @Transaction<br>    suspend fun upsertPhotoPage(<br>        entities: List&lt;PhotoEntity&gt;,<br>        isRefresh: Boolean,<br>        page: Int,<br>        pageSize: Int<br>    ) {<br>        if (isRefresh)<br>            clear()        <br><br>        val offset = (page - 1) * pageSize<br>        val nextKey = page + 1<br>        val previousKey = (page - 1).let { if (it &gt; 0) it else null }<br><br>        val keysList = entities.map {<br>            PhotoRemoteKeysEntity(<br>                nextKey = nextKey,<br>                photoId = it.photoId,<br>                previousKey = previousKey<br>            )<br>        }<br>        val orderList = entities.mapIndexed { index, entity -&gt;<br>            PhotoRemoteOrderEntity(<br>                photoId = entity.photoId,<br>                remoteOrder = index + offset<br>            )<br>        }<br><br>        //Upsert the master entities.<br>        upsertPhoto(entities = entities)<br><br>        //Upsert the slave entities.<br>        upsertRemoteKeys(entities = keysList)<br>        upsertRemoteOrder(entities = orderList)<br>    }<br>}<br><br>@Dao<br>interface PhotoItemDao {<br>    @Query(&quot;SELECT * FROM PhotoItemView ORDER BY ${Column.REMOTE_ORDER} ASC&quot;)<br>    fun getEntitiesPagingSource(): PagingSource&lt;Int, PhotoItemView&gt;<br>}</pre><ul><li>For saving a page of fetched data, we must insert the corresponding metadata alongside the data itself. These operations should be performed within a single transaction to prevent unnecessary data invalidation.</li><li>To generate the PagingSource, we can use a SELECT query combined with an ORDER BY clause on the database view created earlier.</li><li>We also need to be able to clear items when a LoadType.REFRESH is triggered. Thanks to the foreign key declarations, we only need to delete the items from the primary table to trigger a cascade delete of the remote keys and remote order entities.</li><li>Finally, to allow the RemoteMediator to fetch new pages via the API, we need a mechanism to retrieve the corresponding remote keys for any given item.</li></ul><h4>Remote Mediator</h4><pre>class PhotoRemoteMediator(<br>    private val plantName: String,<br>    sunflowerCloneDatabase: SunflowerCloneDatabase,<br>    private val unsplashService: UnsplashService<br>) : RemoteMediator&lt;Int, PhotoItemView&gt;() {<br>    private val photoDao = sunflowerCloneDatabase.photoDao()<br><br>    override suspend fun load(<br>        loadType: LoadType,<br>        state: PagingState&lt;Int, PhotoItemView&gt;<br>    ): MediatorResult {<br>        return try {<br>            val loadKey = when (loadType) {<br>                LoadType.REFRESH -&gt; {<br>                    val remoteKeys = getRemoteKeysClosestToCurrentPosition(state)<br>                    <br>                    // Load the first page if remoteKeys is null.<br>                    remoteKeys?.nextKey?.minus(1) ?: 1<br>                }<br><br>                LoadType.PREPEND -&gt; {<br>                    val remoteKeys = getRemoteKeysForFirstItem(state)<br>                    // If remoteKeys is null, that means the refresh result is not in the database yet.<br>                    // We can return Success with &#39;endOfPaginationReached = false&#39; because Paging<br>                    // will call this method again if RemoteKeys becomes non-null.<br>                    // If remoteKeys is NOT NULL but its previousKey is null, that means we&#39;ve reached<br>                    // the end of pagination for prepend.<br>                    val previousKey = remoteKeys?.previousKey<br>                        ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)<br><br>                    previousKey<br>                }<br><br>                LoadType.APPEND -&gt; {<br>                    val remoteKeys = getRemoteKeysForLastItem(state)<br>                    // If remoteKeys is null, that means the refresh result is not in the database yet.<br>                    // We can return Success with &#39;endOfPaginationReached = false&#39; because Paging<br>                    // will call this method again if RemoteKeys becomes non-null.<br>                    // If remoteKeys is NOT NULL but its nextKey is null, that means we&#39;ve reached<br>                    // the end of pagination for append.<br>                    val nextKey =<br>                        remoteKeys?.nextKey ?: return MediatorResult.Success(<br>                            endOfPaginationReached = remoteKeys != null<br>                        )<br><br>                    nextKey<br>                }<br>            }<br>            // Suspending network load via Retrofit. This doesn&#39;t need to<br>            // be wrapped in a withContext(Dispatcher.IO) { ... } block<br>            // since Retrofit&#39;s Coroutine CallAdapter dispatches on a<br>            // worker thread.<br>            val itemList = getRemoteItems(<br>                isRefresh = loadType == LoadType.REFRESH,<br>                page = loadKey, <br>                pageSize = state.config.pageSize<br>            )<br><br>            MediatorResult.Success(endOfPaginationReached = itemList.isEmpty())<br>        } catch (e: Throwable) {<br>            MediatorResult.Error(e)<br>        }<br>    }<br><br>    private suspend fun getRemoteItems(isRefresh: Boolean, page: Int, pageSize: Int) =<br>        unsplashService.searchPhotos(<br>            page = page,<br>            perPage = pageSize,<br>            query = plantName<br>        ).map {<br>            it.toPhotoEntity(plantName = plantName)<br>        }.also {<br>            photoDao.upsertPhotoPage(<br>                entities = it,<br>                isRefresh = isRefresh,<br>                page = page,<br>                pageSize = pageSize<br>            )<br>        }<br><br>    private suspend fun getRemoteKeysClosestToCurrentPosition(<br>        state: PagingState&lt;Int, PhotoItemView&gt;<br>    ) = with(state) {<br>        anchorPosition?.let { closestItemToPosition(it) }<br>            ?.let {<br>                photoDao.getRemoteKeys(photoId = it.photoId)<br>            }<br>    }<br><br><br>    private suspend fun getRemoteKeysForFirstItem(<br>        state: PagingState&lt;Int, PhotoItemView&gt;<br>    ) = with(state) {<br>        firstItemOrNull()?.let {<br>            photoDao.getRemoteKeys(photoId = it.photoId)<br>        }<br>    }<br><br>    private suspend fun getRemoteKeysForLastItem(<br>        state: PagingState&lt;Int, PhotoItemView&gt;<br>    ) = with(state) {<br>        lastItemOrNull()?.let {<br>            photoDao.getRemoteKeys(photoId = it.photoId)<br>        }<br>    }<br>}</pre><ul><li>For LoadType.REFRESH, we can use the anchorPosition from the PagingState to find the corresponding item to get its remote keys. If the remote keys are not found, it indicates that there is no position to restore. In this case, we should load the first page instead.</li><li>For LoadType.PREPEND, we can use the first item in the PagingState to retrieve the remote keys required for loading the previous page. If the remote keys are not found, it indicates that there are no items currently in the PagingState. If the previous key within the remote keys is null, it means there is no previous page to load.</li><li>For LoadType.APPEND, we can use the last item in the PagingState to retrieve the required remote keys. If the remote keys are not found, it indicates that there are no items currently in the PagingState. If the next key within the remote keys is null, it means there is no next page to load.</li><li>After a successful fetch, we need to check if the boundary has been reached to avoid triggering another data fetch. This is determined by checking whether the fetched data is empty.</li><li>Since we are making API calls, we should handle exceptions by using a try-catch block to return a failure result.</li></ul><h4>Repository</h4><pre>class PhotoRepositoryImp(<br>    private val sunflowerCloneDatabase: SunflowerCloneDatabase,<br>    private val unsplashService: UnsplashService<br>) : PhotoRepository {<br>    private val photoItemDao = sunflowerCloneDatabase.photoItemDao()<br>    override fun getPhotoPagingDataFlow(plantName: String): Flow&lt;PagingData&lt;PhotoDO&gt;&gt; = Pager(<br>        config = PagingConfig(pageSize = 25),<br>        remoteMediator = PhotoRemoteMediator(<br>            plantName = plantName,<br>            sunflowerCloneDatabase = sunflowerCloneDatabase,<br>            unsplashService = unsplashService<br>        )<br>    ) {<br>        photoItemDao.getEntitiesPagingSource()<br>    }.flow.map { pagingData -&gt;<br>        pagingData.map {<br>            it.toPhotoDO(<br>                attributionUrl = unsplashService.getAttributionUrl(userName = it.authorId)<br>            )<br>        }<br>    }<br>}</pre><ul><li>In the repository, we can combine the PagingSource and RemoteMediator using a Pager to create a PagingData flow.</li><li>To adhere to Domain-Driven Design principles, database entities are mapped to domain models (PhotoDO) to prevent internal data structures from leaking into outer layers.</li></ul><h4>View Model</h4><pre>@HiltViewModel<br>class GalleryViewModel @Inject constructor(<br>    private val photoRepository: PhotoRepository,<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    private val _stateFlow = MutableStateFlow&lt;State&gt;(savedStateHandle[KEY_STATE]!!)<br>    val stateFlow = _stateFlow.asStateFlow()<br><br>    private var state: State<br>        get() = stateFlow.value<br>        set(value) {<br>            _stateFlow.update { value }<br><br>            savedStateHandle[KEY_STATE] = value<br>        }<br><br>    val photoPagingDataFlow = createPhotoPagingDataFlow().cachedIn(viewModelScope)<br><br>    fun goBack() {<br>        state = state.copy(actions = state.actions + State.Action.GoBack)<br>    }<br><br>    fun onAction(action: State.Action) {<br>        state = state.copy(actions = state.actions - action)<br>    }<br><br>    fun openWebLink(url: String) {<br>        state = state.copy(actions = state.actions + State.Action.OpenWebLink(url = url))<br>    }<br><br>    private fun createPhotoPagingDataFlow() =<br>        stateFlow.flatMapLatest { state -&gt;<br>            photoRepository.getPhotoPagingDataFlow(plantName = state.plantName)<br>        }<br><br>    companion object {<br>        private const val TAG = &quot;GalleryViewModel&quot;<br>        private const val KEY_STATE = &quot;$TAG.KEY_STATE&quot;<br><br>        internal fun createArgs(plantName: String) = Bundle().apply {<br>            putParcelable(KEY_STATE, State(plantName = plantName))<br>        }<br>    }<br><br>    @Parcelize<br>    data class State(val actions: List&lt;Action&gt; = emptyList(), val plantName: String) : Parcelable {<br>        sealed interface Action : Parcelable {<br>            @Parcelize<br>            data object GoBack : Action<br><br>            @Parcelize<br>            data class OpenWebLink(val url: String) : Action<br>        }<br>    }<br>}</pre><ul><li>In the view model, we can use flatMapLatest() to dynamically transform the view model state flow into a PagingData flow.</li><li>The cachedIn() operator ensures the PagingData cache survives configuration changes such as screen rotation by scoping the cache to the viewModelScope.</li></ul><h4>View</h4><pre>@Composable<br>fun GalleryScreen(<br>    onGoBack: () -&gt; Unit,<br>    viewModel: GalleryViewModel = hiltViewModel()<br>) {<br>    val context = LocalContext.current<br>    val state = viewModel.stateFlow.collectAsState().value<br><br>    val actions = state.actions<br><br>    LaunchedEffect(actions) {<br>        actions.forEach { action -&gt;<br>            when (action) {<br>                GalleryViewModel.State.Action.GoBack -&gt; onGoBack()<br>                is GalleryViewModel.State.Action.OpenWebLink -&gt; openWebLink(context, action.url)<br>            }<br><br>            viewModel.onAction(action)<br>        }<br>    }<br><br>    GalleryLayout(<br>        photos = viewModel.photoPagingDataFlow.collectAsLazyPagingItems(),<br>        onBackClick = { viewModel.goBack() },<br>        onPhotoClick = { viewModel.openWebLink(url = it.attributionUrl) })<br>}<br><br>private fun openWebLink(context: Context, url: String) {<br>    try {<br>        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))<br>    } catch (e: ActivityNotFoundException) {<br>        Toast.makeText(<br>            context,<br>            R.string.gallery_toast_unable_to_open_link,<br>            Toast.LENGTH_LONG<br>        ).show()<br>    }<br>}</pre><ul><li>The collectAsLazyPagingItems() extension allows us to convert the PagingData flow into LazyPagingItems which can be used with components like LazyColumn or LazyVerticalGrid to display the items.</li></ul><h4>Layout</h4><pre>@Composable<br>fun GalleryLayout(<br>    photos: LazyPagingItems&lt;PhotoDO&gt;,<br>    onBackClick: () -&gt; Unit,<br>    onPhotoClick: (PhotoDO) -&gt; Unit<br>) {<br>    LazyVerticalGrid(<br>        columns = GridCells.Fixed(2),<br>        modifier = Modifier.fillMaxSize(),<br>        contentPadding = PaddingValues(<br>            horizontal = 8.dp,<br>            vertical = 16.dp<br>        )<br>    ) {<br>        items(count = photos.itemCount) { index -&gt;<br>            val photo = photos[index]<br><br>            if (photo != null) {<br>                GalleryItem(<br>                    imageUrl = photo.imageUrl,<br>                    photographer = photo.authorName,<br>                    onClick = { onPhotoClick(photo) }<br>                )<br>            }<br>        }<br>    }<br>}</pre><ul><li>In the layout composable, we can pass photos.itemCount to the items() function of the lazy grid. This allows the grid to display the items just like using a standard list.</li></ul><h3>Pros, and Cons</h3><h4>Pros:</h4><ol><li><strong>Automated Paging Source Implementation:</strong> <br>Generating a PagingSource with Room requires no manual implementation beyond writing a standard SQL statement. This minimizes errors if you are familiar with SQL syntax.</li><li><strong>Streamlined Remote Integration:</strong> <br>Using a Room database as the local source allows you to focus exclusively on implementing the RemoteMediator. The framework handles the complexities of observing data changes and invalidating the UI when new data is fetched.</li></ol><h4>Cons:</h4><ol><li><strong>Complex Load Type Requirements:</strong> <br>While RemoteMediator only requires handling three load types, implementing them correctly requires specialized knowledge. For instance, determining exactly which item index to use as a reference for each load type is not inherently provided by the library.</li><li><strong>Metadata Storage Overhead:</strong> <br>Supplementary information such as remote keys and remote order must be persisted. This necessitates managing additional tables that are strictly coupled with your primary data entities.</li></ol><h3>Conclusion</h3><p>Implementing pagination with Paging 3 and Room significantly reduces implementation complexity compared to using Paging 3 alone. It also allows us to utilize the performance of an SQLite database to provide a smooth UI experience. However, this approach requires familiarity with SQL syntax which may represent a slight learning curve for some. For data-intensive applications, the benefits of pagination make this approach well worth the consideration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fba726d4e05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Obfuscation: Random Class Name Generation]]></title>
            <link>https://medium.com/@b9915034/dynamic-obfuscation-random-class-name-generation-9feb8fa3fc23?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9feb8fa3fc23</guid>
            <category><![CDATA[proguard]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 08:24:00 GMT</pubDate>
            <atom:updated>2026-03-10T06:33:01.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*pm9MyLWZM4ocVibsOPat6A.png" /><figcaption>Dynamic Obfuscation Overview</figcaption></figure><p>This article explains how to apply dynamic ProGuard obfuscation dictionary while assembling minified applications. Note: Edited in 2026/3/10</p><h3>Introduction</h3><blockquote>How can obfuscated class names be made less predictable than simply using alphabets?</blockquote><p>It is common practice for Android developers to minify their APKs before publication. The default dictionary is composed of English characters, and is usually sufficient for this task. However, due to the small pool size and short name length, the obfuscation results are highly predictable.</p><h3>Overview</h3><h4>Obfuscation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*b6oyndTFglV-yMYxPB_23A.png" /><figcaption>ProGuard Obfuscation Illustration</figcaption></figure><p>Obfuscation is a process that strips actual names and replaces them with meaningless ones:</p><ul><li>It is mainly done for the purpose of protecting intellectual property by increasing the effort required for reverse engineering.</li><li>Even though the names are changed, the behavior remains the same, so the application functions just like its non-obfuscated version.</li><li>However, the same functionality is not guaranteed because names can be used in the logic of program. Any mismatch can easily cause the application to crash.</li><li>A common example of this is Retrofit which uses reflection to map responses and requests into data classes. JSON keys are very unlikely to match obfuscated names.</li><li>ProGuard rules are used to keep certain names in order to avoid this problem.</li></ul><blockquote>Nowadays, almost every public application uses obfuscation. The strength of resistance to reverse engineering depends on how the rules are configured.</blockquote><h4>Dictionary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*soIDykDsH_hXEhwgORCntw.png" /><figcaption>Dictionary in Obfuscation Process</figcaption></figure><p>It is possible to provide custom dictionaries for obfuscation by declaring specific ProGuard rules:</p><ul><li>The default dictionary used by ProGuard is composed of English characters, each listed on a separate line.</li><li>In practice, the class GardenPlantingRepository can be renamed to a, b, aa, or any other combination of the characters.</li><li>This makes the names highly predictable because the pool of words is small, and the words are short.</li><li>A custom dictionary can have a much larger pool and can use words instead of single characters.</li></ul><blockquote>Using a custom dictionary can make it harder for a human to read through your code. However, because the output of ProGuard is deterministic, it does not generate significantly different mappings for each build. This stability makes it possible to analyze changes across different code versions.</blockquote><h4>Randomization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*QyXKB662mVarkFULi0g7rQ.png" /><figcaption>Dictionary Shuffling</figcaption></figure><p>To ensure the builds are not identical to each other, we can generate a new dictionary for each build:</p><ul><li>Gradle allows you to define custom tasks that run after project evaluation which can be used to generate a new dictionary</li><li>In the task, we need to generate the dictionary, and the ProGuard rule file that applies the generated dictionary.</li><li>Gradle can merge multiple ProGuard files to ensure that the generated dictionary can work with existing rules.</li><li>A common approach is to use a base dictionary during generation, then shuffle it to produce a new dictionary for each build.</li></ul><blockquote>Generating a new dictionary for every new build solves the problem of similarity. This practice prevents an attacker from applying insights gained from previous efforts to subsequent builds.</blockquote><h3>Implementation Details</h3><h4>Obfuscation Dictionary</h4><pre>Apple<br>Bridge<br>Cloud<br>Dream<br>Eagle<br>Forest<br>Garden<br>Harmony<br>Idea<br>Journey<br>Knowledge<br>Light<br>Mountain<br>Nature<br>Ocean<br>Peace<br>Quest<br>River<br>Stars<br>Travel<br>Unity<br>Vision<br>Wisdom<br>Xenial<br>Youth<br>Zephyr</pre><ul><li>This is an example of an obfuscation dictionary. Each entry is separated by line, and the number of entries is not limited.</li><li>White space, punctuation characters, duplicate words, and comments after a # sign are ignored. Duplicate entries are not allowed.</li><li>It is possible to use something like reserved Java keywords in an obfuscation dictionary, but it provides little benefit since a decent decompiler can automatically rename illegal identifiers.</li><li>Including a vast number of exceptionally long words can help, but the impact is limited because an attacker can simply re-obfuscate the code.</li><li>It is a common practice to use a seed dictionary to generate a new dictionary for every build by shuffling and partitioning the words.</li></ul><h4>ProGuard Rules</h4><pre>-obfuscationdictionary &lt;filename&gt;<br>-classobfuscationdictionary &lt;filename&gt;<br>-packageobfuscationdictionary &lt;filename&gt;</pre><ul><li>The -obfuscationdictionary rule specifies a file containing the words used to obfuscate field and method names.</li><li>-classobfuscationdictionary is similar to -obfuscationdictionary, but the words are used to obfuscate class names.</li><li>-packageobfuscationdictionary allows you to provide a dictionary for obfuscating package names.</li><li>ProGuard accepts absolute paths and relative paths for the various file names and directory names.</li><li>In this case, we’ll use the absolute path since we’re generating the ProGuard rule file ourselves.</li></ul><h4>Gradle Task Registration</h4><pre>subprojects {<br>    pluginManager.withPlugin(&quot;com.android.application&quot;) {<br>        // This is the original dictionary used to generate the new version.<br>        val inputDictionary = file(&quot;proguard-dictionary.txt&quot;)<br><br>        // The output directory where generated files are stored.<br>        val dictionaryDir = layout.buildDirectory.dir(&quot;generated/proguard&quot;)<br><br>        // The shuffled version of the input dictionary.<br>        val dictionaryFile = dictionaryDir.map { it.file(&quot;proguard-dictionary.txt&quot;) }<br><br>        // ProGuard rules used to apply the generated dictionary.<br>        val ruleFile = dictionaryDir.map { it.file(&quot;auto-dictionary-rules.pro&quot;) }<br><br>        val generateObfuscationDictionaryTask =<br>            tasks.register(&quot;generateObfuscationDictionary&quot;) {<br>                with(inputs) {<br>                    file(inputDictionary)<br>                }<br><br>                with(outputs) {<br>                    file(dictionaryFile)<br>                    file(ruleFile)<br><br>                    // We want to generate a new dictionary for every build.<br>                    upToDateWhen { false }<br>                }<br><br>                // Only perform dictionary generation when the task is called.<br>                doLast {<br>                    val lines = inputDictionary.readLines().filter { it.isNotBlank() }<br>                        .toMutableList().apply { shuffle() }<br><br>                    val outDict = dictionaryFile.get().asFile.apply {<br>                        parentFile.mkdirs()<br><br>                        writeText(lines.joinToString(&quot;\n&quot;))<br>                    }<br><br>                    ruleFile.get().asFile.writeText(<br>                        &quot;&quot;&quot;<br>                        # Auto-generated.<br>                        -obfuscationdictionary &quot;${outDict.absolutePath}&quot;<br>                        -classobfuscationdictionary &quot;${outDict.absolutePath}&quot;<br>                        -packageobfuscationdictionary &quot;${outDict.absolutePath}&quot;<br>                        &quot;&quot;&quot;.trimIndent()<br>                    )<br>                }<br>            }<br><br>        val android = extensions.getByType(com.android.build.gradle.AppExtension::class.java)<br><br>        android.applicationVariants.configureEach {<br>            // Skip the task when there is no input dictionary.<br>            // This makes applying custom dictionary optional.<br>            if (buildType.isMinifyEnabled &amp;&amp; inputDictionary.exists()) {<br>                // This ensures the task runs before the build starts.<br>                preBuildProvider.configure {<br>                    dependsOn(generateObfuscationDictionaryTask)<br>                }<br><br>                // Ensures minification runs for every generated dictionary.<br>                tasks.matching {<br>                    it.name.startsWith(&quot;minify&quot;) &amp;&amp; it.name.endsWith(&quot;WithR8&quot;)<br>                }.configureEach {<br>                    inputs.file(dictionaryFile)<br>                }<br>            }<br>        }<br>    }<br>}</pre><ul><li>This project-level script registers a task that shuffles the proguard-dictionary.txt file, and creates an auto-dictionary-rules.pro file used to apply the generated dictionary during obfuscation.</li><li>The task is executed only when the com.android.application plugin is applied, and minifyEnabled is set to true.</li><li>The script also makes the minification task depend on the output of this task, so that every generated dictionary is applied.</li><li>In this setup, each application module can have its own proguard-dictionary.txt stored alongside the module-level build.gradle.kts file for customization.</li><li>Default obfuscation can still be applied by removing proguard-dictionary.txt from the target modules without modifying the script.</li></ul><h4>ProGuard Rule Integration</h4><pre>android {<br>    //...//<br><br>    buildTypes {<br>        getByName(&quot;release&quot;) {<br>            isMinifyEnabled = true<br><br>            proguardFiles(<br>                getDefaultProguardFile(&quot;proguard-android-optimize.txt&quot;),<br>                &quot;proguard-rules.pro&quot;,<br>                // This is the .pro file generated by the task.<br>                &quot;${layout.buildDirectory.get()}/generated/proguard/auto-dictionary-rules.pro&quot;<br>            )<br>        }<br>    }<br>}</pre><ul><li>This module-level script includes the task-generated ProGuard file. It should be placed in the app module Gradle.</li><li>If proguard-rules.pro also contains an -obfuscationdictionary rule, it will be overridden by the one provided in auto-dictionary-rules.pro.</li><li>Because Gradle processes ProGuard files in the order they are declared, the final definition overrides previous ones.</li></ul><h3>Pros, and Cons</h3><h4>Pros</h4><ol><li><strong>Increased Effort for Cross-Version Analysis:<br></strong>As mentioned earlier, each build will have far fewer similarities in name mappings. Even if an attacker re-obfuscates both versions, they will not produce similar results because the original input names directly influence the mapping.</li><li><strong>Resistance to Dictionary Attacks:</strong><br>The default dictionary uses alphabets in a lexicographical order. Attackers can exploit this well-known sequence to make educated guesses about the meaning of obfuscated names. By using a dynamic dictionary, the naming order becomes randomized.</li></ol><h4>Cons</h4><ol><li><strong>Debugging Complexity:<br></strong>Just as it complicates things for an attacker, custom mappings make it less convenient for developers to navigate the code. While this can be mitigated through careful dictionary design, such an approach may also inadvertently make things easier for an attacker.</li><li><strong>Broken Incremental Compilation:<br></strong>Typically, Gradle’s incremental build system is effective because ProGuard’s output is deterministic. However, changing the dictionary for every build forces a complete re-compilation which can significantly increase build times. That said, this may not be a major issue since developers rarely debug using release builds, and dynamic obfuscation can be disabled during the development process.</li></ol><h3>Conclusion</h3><p>Almost every app publication involves obfuscation. Some projects require high security, and demand the use of dynamic dictionary. While this does complicate things for attackers, it rarely stops a determined adversary from reverse-engineering your implementation. You should evaluate your specific needs to decide whether or not to apply this technique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9feb8fa3fc23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Progressive Migration to LMA: An Incremental Approach to Clean Architecture]]></title>
            <link>https://medium.com/@b9915034/progressive-migration-to-lma-an-incremental-approach-to-clean-architecture-40e7f7d5b79e?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e7f7d5b79e</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[migration-strategies]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 05:40:31 GMT</pubDate>
            <atom:updated>2026-02-04T08:21:43.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*j-Kn3YZj2TCs8mNboVoEGQ.png" /><figcaption>Progressive Migration Overview</figcaption></figure><p>This article explores a step-by-step approach to migrating from a legacy architecture to a Layered Modular Architecture. Note: Edited in 2026/2/4.</p><h3>Introduction</h3><blockquote>How can you escape legacy hell if you can’t afford a complete overhaul?</blockquote><p>It’s a common problem that many systems still run on outdated architectures. A straightforward solution is to rewrite everything from scratch, so you can adopt new designs without getting tangled. In most cases, we don’t have the luxury to start over. If only there were a way to modernize without having to do everything at once.</p><h3>Architectural Design Overview</h3><h4>Progressive Migration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*j-Kn3YZj2TCs8mNboVoEGQ.png" /><figcaption>Progressive Migration Overview</figcaption></figure><p>Progressive migration means gradually replacing an existing system while ensuring that the system remains functional at every step:</p><ul><li>A full migration that involves a complete overhaul often conflicts with delivery schedules. It is desirable to be able to deliver new features while upgrading the system at the same time.</li><li>One common approach is to introduce an interface, and gradually replace the legacy implementation behind it. This technique is also known as the Strangler Fig Pattern.</li><li>For example, a composable can be integrated into a XML layout by using a ComposeView without heavily interfering with the existing UI.</li></ul><blockquote>Refactoring a legacy application all at once is often too costly. It is better to break down the migration effort into smaller phases that easily fit into development schedules.</blockquote><h4>Componentization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*UyebXcBoEsNb0sGnI_oDVg.png" /><figcaption>Componentization Illustration</figcaption></figure><p>Progressive migration involves transitioning through intermediate states. Suspend points such as components are required to define the steps:</p><ul><li>How we split the codebase into components depends on what architecture we’re aiming for. For instance, if we organize code by feature, then each feature module will act as a component.</li><li>Components shouldn’t be too fine-grained because that creates integration overhead. Nor should they be too coarse-grained to avoid implementing too much to reach the next stable build.</li><li>The goal is to be able to implement at least one component in each development cycle, so we can migrate part of the legacy code in free time.</li></ul><blockquote>Componentization is a necessary step for progressive migration because it allows us to use short time windows to maintain steady migration progress. With these characteristics in mind, we can evaluate our architecture options.</blockquote><h4>Architecture Choice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*9enJ6pnG-gvc6bsEMx_0vg.png" /><figcaption>Problem of Modularization by Feature</figcaption></figure><p>Modularization by feature is a commonly adopted strategy for componentization, but treating a feature as a component is not always a clean cut:</p><ul><li>Features can vary greatly in scope and complexity. One might consist of a single page with little information while another could involve multiple screens and real-time feeds.</li><li>For complex features, implementing one often takes too much time to fit within a single sprint, and it is easy to duplicate implementations across components.</li><li>The desirable traits of a component are being non-duplicative, reusable, and properly scoped. This allows us to maintain a stable build with every incremental delivery.</li></ul><blockquote>Modularization by feature may not be ideal for progressive migration because feature boundaries are not always clear. We therefore need a new architectural approach that provides better componentization.</blockquote><h4>Layered Modular Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*LRiz8AwXraVXhX80TmIfYQ.png" /><figcaption>Modularization in LMA</figcaption></figure><p>Layered Modular Architecture (LMA) is an extension of Clean Architecture. It introduces a revised modularization strategy while preserving the core concepts:</p><ul><li>LMA uses a hybrid approach which first divides the system by layer, and then by feature. It allows each layer to define its own domain scope, and make it possible to further divide the layer into reusable modules.</li><li>In this case, a new feature can often reuse existing components thanks to the separation of layers. Ideally, you only need to implement the feature module by reusing the existing components.</li><li>Under modularization by feature, you might have a :feature:profile module that contains its own UI, domain (e.g., UpdateUserUseCase), and data (e.g., UserRepository). If a new :feature:settings also needs to update the user, it either depends on :feature:profile, or duplicates the logic.</li><li>For LMA, you would have :domain:user (contains UpdateUserUseCase, UserRepository interface), :data:user (contains the implementation of UserRepository), :feature:profile (UI, depends on :domain:user), and :feature:settings (UI, also depends on :domain:user)</li><li>LMA makes the business logic (:domain:user) an independent component that both features can consume without depending on each other. This componentization makes progressive migration more feasible.</li><li>For details about LMA, check out the blog: <a href="https://medium.com/@b9915034/android-application-architecture-showcase-sunflower-clone-dee729f6e1f2"><strong>Layered Modular Architecture: Evolving Clean Architecture to Support Multiplatform Development</strong></a></li></ul><blockquote>LMA provides more fine-grained components that are highly reusable. Whether creating a new feature or migrating an existing one, the process can be done incrementally.</blockquote><h4>Legacy Code Handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*vmIrjo8c95p4Jrq8HfTNFw.png" /><figcaption>Logic Extraction from Legacy Code</figcaption></figure><p>LMA allows you to postpone modularization until it provides real value. During migration, the legacy code can be treated as the starting app module:</p><ul><li>To refactor parts of the legacy code, you can create new components that replicate the same logic and then replace the corresponding usages in the app module.</li><li>The main bottleneck for refactoring is shared code. It is better to prioritize refactoring the most shared logic such as the design system, database layer, and API clients.</li><li>This helps avoid logic duplication and reduces the effort required when any code that uses shared code is later migrated.</li></ul><blockquote>In LMA, an app module serves as the assembly point that has access to all dependencies. This allows a legacy application to be treated as one. From this foundation, you can develop new LMA modules to scale or refactor the original project.</blockquote><h4>Limitation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*8SS6lMDuGXACgvV_svcumA.png" /><figcaption>Handling Prioritized Feature Development</figcaption></figure><p>Sometimes, you may need to prioritize new feature development even if those features depend on legacy code:</p><ul><li>In such cases, the required dependencies may not yet be reusable outside the app module. This makes it not feasible to modularize the new feature right away.</li><li>However, you can still apply layer separation within the app module to prepare for future migration.</li><li>For example, suppose AuthManager which stores the token required for API calls is implemented in the app module. You can’t move API-related logic into a dedicated data module, but you can still create temporary implementations within the app module.</li><li>This approach doesn’t break the architecture rules, but it loses the advantages of modularization because everything remains inside the app module.</li></ul><blockquote>When delivery schedules conflict with your refactoring roadmap, it’s acceptable to implement the new feature temporarily within the app module. As long as it follows the architectural layering pattern and is planned for later migration.</blockquote><h3>Implementation Details</h3><h4>Domain Declaration</h4><pre>// Domain model of garden planting<br>data class GardenPlantingDO(<br>    val description: String?,<br>    val gardenPlantingId: Int,<br>    val growZoneNumber: Int?,<br>    val imageUrl: String?,<br>    val plantDate: Long,<br>    val plantId: String,<br>    val plantName: String?,<br>    val wateringIntervalDays: Int?<br>)<br><br>// Repository interface for accessing garden planting data<br>interface GardenPlantingRepository {<br>    suspend fun addGardenPlanting(plantDate: Long, plantId: String)<br>    fun getGardenPlantingPagingDataFlow(): Flow&lt;PagingData&lt;GardenPlantingDO&gt;&gt;<br>}<br><br>// Use case for encapsulating extra business logic<br>class AddGardenPlantingUseCase(private val repository: GardenPlantingRepository) {<br>    suspend operator fun invoke(plantId: String) {<br>        // Get current timestamp<br>        val plantDate = Clock.System.now().toEpochMilliseconds()<br><br>        repository.addGardenPlanting(plantDate = plantDate, plantId = plantId)<br>    }<br>}</pre><ul><li>Domain contracts are the in-code representation of the real business domain. The main purpose of this separation is to decouple the UI from the data implementation so that feature modules and data modules can remain independently reusable.</li><li>A domain module typically consists of three major parts which are data models, repositories, and use cases.</li><li>In the example above, the requirement is to allow the user to save a garden planting with the current timestamp. Therefore, we define GardenPlatningDO as the data model, GardenPlatningRepository as the contract for accessing planting data, and AddGardenPlantingUseCase as the operation that performs the business logic.</li><li>This creates a stable interface for your legacy code to continue to function while modularized features are built against these same contracts, allowing for a gradual swap-out.</li></ul><h4>Core Infrastructure</h4><pre>// Application database<br>@Database(<br>    entities = [<br>        GardenPlantingEntity::class,<br>        PhotoEntity::class,<br>        PhotoRemoteKeysEntity::class,<br>        PhotoRemoteOrderEntity::class,<br>        PlantEntity::class<br>    ],<br>    version = 1,<br>    views = [<br>        GardenPlantingItemView::class,<br>        PhotoItemView::class,<br>        PlantItemView::class<br>    ]<br>)<br>abstract class SunflowerCloneDatabase : RoomDatabase() {<br>    abstract fun gardenPlantingDao(): GardenPlantingDao<br>    abstract fun gardenPlantingItemDao(): GardenPlantingItemDao<br>    abstract fun photoDao(): PhotoDao<br>    abstract fun photoItemDao(): PhotoItemDao<br>    abstract fun plantDao(): PlantDao<br>    abstract fun plantItemDao(): PlantItemDao<br>}</pre><ul><li>There may also be domain-free infrastructures required to support the domain contracts. For example, a database may expose different DAOs while joining multiple tables under the hood.</li><li>These kinds of infrastructures are usually referenced by multiple features or data implementations. Without separating them, data implementations become tightly coupled and components can grow too large to fit within a development cycle.</li><li>Isolating core components like the database allows you to migrate one piece of the data layer at a time without breaking other parts.</li></ul><h4>Data Implementation</h4><pre>// Implementation of the access to the GardenPlanting model<br>class GardenPlantingRepositoryImp(<br>    sunflowerCloneDatabase: SunflowerCloneDatabase<br>) : GardenPlantingRepository {<br>    private val gardenPlantingDao = sunflowerCloneDatabase.gardenPlantingDao()<br>    private val gardenPlantingItemDao = sunflowerCloneDatabase.gardenPlantingItemDao()<br><br>    override suspend fun addGardenPlanting(plantDate: Long, plantId: String) {<br>        gardenPlantingDao.upsert(<br>            listOf(GardenPlantingEntity(plantDate = plantDate, plantId = plantId))<br>        )<br>    }<br><br>    override fun getGardenPlantingPagingDataFlow(): Flow&lt;PagingData&lt;GardenPlantingDO&gt;&gt; = Pager(<br>        config = PagingConfig(pageSize = 25)<br>    ) {<br>        gardenPlantingItemDao.getEntitiesPagingSource()<br>    }.flow.map { pagingData -&gt; pagingData.map { it.toGardenPlantingDO() } }<br>}</pre><ul><li>With the domain contracts and infrastructures in place, we can now implement the actual data access.</li><li>The main responsibility is to integrate the underlying data sources and map the DTOs produced by the infrastructures into the domain models defined in the contracts.</li><li>Because this module just implements an interface from the domain layer, you can have the legacy data access and this new data module coexist. You can slowly direct more and more of the data to use the new implementation with dependency injection.</li></ul><h4>Feature Integration</h4><pre>// The entry point of the garden planting list page<br>@Composable<br>fun GardenPlantingListScreen(<br>    onGoToPlantDetailsScreen: (plantId: String) -&gt; Unit,<br>    viewModel: GardenPlantingListViewModel = hiltViewModel()<br>) {<br>    val actions = viewModel.stateFlow.collectAsState().value.actions<br><br>    LaunchedEffect(actions) {<br>        actions.forEach { action -&gt;<br>            when (action) {<br>                is GardenPlantingListViewModel.State.Action.GoToPlantDetailsScreen -&gt; onGoToPlantDetailsScreen(<br>                    action.plantId<br>                )<br>            }<br><br>            viewModel.onAction(action)<br>        }<br>    }<br><br>    GardenPlantingListLayout(<br>        plants = viewModel.gardenPlantingPagingDataFlow.collectAsLazyPagingItems(),<br>        onPlantClick = { viewModel.goToPlantDetailsScreen(plantId = it.plantId) }<br>    )<br>}<br><br>// The view model paired with the page<br>@HiltViewModel<br>class GardenPlantingListViewModel @Inject constructor(<br>    private val gardenPlantingRepository: GardenPlantingRepository,<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    private val _stateFlow = MutableStateFlow(savedStateHandle[KEY_STATE] ?: State())<br>    val stateFlow = _stateFlow.asStateFlow()<br><br>    private var state: State<br>        get() = stateFlow.value<br>        set(value) {<br>            _stateFlow.update { value }<br><br>            savedStateHandle[KEY_STATE] = value<br>        }<br><br>    val gardenPlantingPagingDataFlow = createGardenPlantingPagingDataFlow().cachedIn(viewModelScope)<br><br>    fun goToPlantDetailsScreen(plantId: String) {<br>        state =<br>            state.copy(actions = state.actions + State.Action.GoToPlantDetailsScreen(plantId = plantId))<br>    }<br><br>    fun onAction(action: State.Action) {<br>        state = state.copy(actions = state.actions - action)<br>    }<br><br>    private fun createGardenPlantingPagingDataFlow() =<br>        gardenPlantingRepository.getGardenPlantingPagingDataFlow()<br><br>    companion object {<br>        private const val TAG = &quot;GardenPlantingListViewModel&quot;<br>        private const val KEY_STATE = &quot;$TAG.KEY_STATE&quot;<br>    }<br><br>    @Parcelize<br>    data class State(val actions: List&lt;Action&gt; = emptyList()) : Parcelable {<br>        sealed interface Action : Parcelable {<br>            @Parcelize<br>            data class GoToPlantDetailsScreen(val plantId: String) : Action<br>        }<br>    }<br>}</pre><ul><li>Features are quite similar to data implementations in terms of requirements. They also only need the domain contracts and infrastructures in place before they can be implemented.</li><li>The difference is that they consume the domain contracts rather than implement them, and they primarily focus on user interactions and presentation logic.</li><li>Since navigation is delegated to the app layer, you can replace the legacy UI gradually because features in LMA do not depend on each other unless they are nested.</li></ul><h4>Application Assembling</h4><pre>// Database injection<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppDatabaseModule {<br>    @Provides<br>    @Singleton<br>    internal fun provideAppDatabase(@ApplicationContext context: Context) = Room.databaseBuilder(<br>        context,<br>        SunflowerCloneDatabase::class.java,<br>        &quot;sunflower_clone_database&quot;<br>    ).build()<br>}<br><br>// Use case injection<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object GardenPlantingDomainModule {<br>    @Provides<br>    @Singleton<br>    internal fun provideAddGardenPlantingUseCase(gardenPlantingRepository: GardenPlantingRepository): AddGardenPlantingUseCase =<br>        AddGardenPlantingUseCase(repository = gardenPlantingRepository)<br>}<br><br>// Repository injection<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object GardenPlantingRepositoryModule {<br>    @Provides<br>    @Singleton<br>    internal fun provideGardenPlantingRepository(sunflowerCloneDatabase: SunflowerCloneDatabase): GardenPlantingRepository =<br>        GardenPlantingRepositoryImp(sunflowerCloneDatabase = sunflowerCloneDatabase)<br>}<br><br>// The top-level activity<br>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br>    private val viewModel: MainActivityViewModel by viewModels()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            val navController = rememberNavController()<br><br>            MainNavHost(navHostController = navController)<br><br>            val actions = viewModel.stateFlow.collectAsState().value.actions<br><br>            LaunchedEffect(actions) {<br>                actions.forEach { action -&gt;<br>                    when (action) {<br>                        MainActivityViewModel.State.Action.GoBack -&gt; navController.popBackStack()<br>                        is MainActivityViewModel.State.Action.GoToScreen -&gt; when (action.screen) {<br>                            is MainScreen.Gallery -&gt; navController.navigate(<br>                                galleryDestination.createLink(<br>                                    action.screen.plantName<br>                                )<br>                            )<br><br>                            is MainScreen.PlantDetails -&gt; navController.navigate(<br>                                plantDetailsDestination.createLink(plantId = action.screen.plantId)<br>                            )<br>                        }<br>                    }<br><br>                    viewModel.onAction(action)<br>                }<br>            }<br>        }<br><br>        configureStatusBar()<br>    }<br><br>    private fun configureStatusBar() {<br>        WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars =<br>            true<br>    }<br><br>    @OptIn(ExperimentalMaterial3Api::class)<br>    @Composable<br>    private fun MainNavHost(navHostController: NavHostController) {<br>        val enterTransition: (AnimatedContentTransitionScope&lt;NavBackStackEntry&gt;.() -&gt; EnterTransition) =<br>            { slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Start, tween(300)) }<br>        val exitTransition: (AnimatedContentTransitionScope&lt;NavBackStackEntry&gt;.() -&gt; ExitTransition) =<br>            { slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.End, tween(300)) }<br><br>        SunflowerCloneTheme {<br>            NavHost(<br>                navController = navHostController,<br>                startDestination = navigationDestination.route,<br>                enterTransition = enterTransition,<br>                exitTransition = exitTransition,<br>                popEnterTransition = enterTransition,<br>                popExitTransition = exitTransition<br>            ) {<br>                composable(<br>                    galleryDestination.route,<br>                    arguments = GalleryDestination.args<br>                ) {<br>                    GalleryScreen(onGoBack = { viewModel.goBack() })<br>                }<br>                composable(navigationDestination.route) {<br>                    NavigationScreen(<br>                        onGoToPlantDetailsScreen = { viewModel.goToPlantDetailsScreen(plantId = it) }<br>                    )<br>                }<br>                composable(<br>                    plantDetailsDestination.route,<br>                    arguments = PlantDetailsDestination.args<br>                ) {<br>                    PlantDetailsScreen(<br>                        onGoBack = { viewModel.goBack() },<br>                        onGoToGalleryScreen = { viewModel.goToGalleryScreen(plantName = it) })<br>                }<br>            }<br>        }<br>    }<br><br>    companion object {<br>        private val galleryDestination = GalleryDestination(&quot;Gallery&quot;)<br>        private val navigationDestination = NavigationDestination(&quot;Navigation&quot;)<br>        private val plantDetailsDestination = PlantDetailsDestination(&quot;PlantDetails&quot;)<br>    }<br>}</pre><ul><li>With all the independent components we created earlier, we need a central point for integration.</li><li>In LMA, the app layer is responsible for injecting the dependencies required by each component. Most of this involves providing data implementations for the domain contracts. Sometimes, we also need to inject core infrastructures that support those data implementations.</li><li>Navigation is also handled in the app layer. The app module typically contains the navigation host and determines which destination to navigate to based on user interactions.</li><li>During migration, we can treat the legacy codebase as the app module and gradually plug in new LMA components as replacements. This allows you to migrate only a small portion of the legacy code at a time, making progressive migration feasible.</li></ul><h3>Pros, and Cons</h3><h4>Pros</h4><ol><li><strong>Reduced Risk Compared to Full Rewrite:<br></strong>A full, one-shot refactor rarely works in practice. Businesses can’t pause feature delivery, and new features added during a rewrite often don’t fit the new architecture. This forces duplicate implementations in both legacy and new systems. Progressive migration avoids it by breaking the work into small phases, with each phase being production-ready.</li><li><strong>Sustainable Migration Compared to Ad Hoc Fixes:<br></strong>Another common migration strategy is to refactor on the fly by only fixing the parts that cause immediate problems. This is less risky than a full rewrite, but the results often remain tangled with the legacy structure and can drift further from the intended architecture over time. LMA prevents this by keeping migrated parts isolated and uninfluenced by future development.</li></ol><h4>Cons</h4><ol><li><strong>Global Configuration Conflict:<br></strong>Even though we aim to refactor only part of the legacy code at a time, some configurations are global and cannot be isolated. Examples include the Android Gradle Plugin (AGP) version, the Kotlin version, and shared library versions. Even with progressive migration, you still need to resolve these dependency conflicts in one pass or compromise by sticking to older frameworks.</li><li><strong>Forced Application of Dependency Injection:<br></strong>Dependency injection (DI) is a core requirement for using LMA. This forces developers to adopt some form of DI, even if it wasn’t previously used in the legacy code. While necessary, it can add some complexity and slightly increase build time.</li></ol><h3>Conclusion</h3><p>LMA was originally created to help me respond quickly to changing requirements. When I later moved to a new role, I found it surprisingly easy to continue using the LMA structure to implement new features in a legacy project.</p><p>Upgrading old systems is always challenging, especially when business priorities place new feature development above architectural improvements. Despite growing inefficiencies, developers are often forced to focus on delivering features rather than refactoring.</p><p>These experiences made me realize that the best solution is continuous migration alongside feature delivery. If I can easily plug new LMA components into legacy code, why not extract legacy logic and rewrite it as LMA components to plug back in?</p><p>In essence, migration may seem intimidating, but breaking it into small, manageable steps makes the process far more approachable.</p><ul><li><a href="https://github.com/Deathhit/SunflowerClone">GitHub - Deathhit/SunflowerClone: Android application architecture example composed of MVVM, UDF and modularization</a></li><li><a href="https://github.com/Deathhit/TaipeiTour/tree/master">GitHub - Deathhit/TaipeiTour: Android application architecture example composed of MVVM, UDF and modularization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e7f7d5b79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline-first Application: Uninterrupted User Experience]]></title>
            <link>https://medium.com/@b9915034/offline-first-application-uninterrupted-user-experience-074727b13491?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/074727b13491</guid>
            <category><![CDATA[task-scheduling]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[data-synchronization]]></category>
            <category><![CDATA[software-patterns]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 06:35:02 GMT</pubDate>
            <atom:updated>2025-10-03T18:04:04.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*ieVho0mPbtPyoz5g_cwzYg.png" /><figcaption>Offline-first Pattern Overview</figcaption></figure><p>This article explores the offline-first pattern and how it can create a seamless UI by minimizing waiting for data. Note: Edited in 2025/10/4.</p><h3>Introduction</h3><blockquote>How can you avoid blocking user interactions while fetching data from the server?</blockquote><p>Have you ever accidentally clicked on a page and been forced to wait for it to load? Or left a page before it finished loading, only to wait again the next time you visit? This frustrating experience happens because data fetching and user interactions are asynchronous but tightly coupled, forcing one to wait for the other.</p><h3>Architectural Design Overview</h3><h4>Offline-first Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Qf4ap-GGZDZWkijTTPDOTA.png" /><figcaption>Offline-first Data Flow</figcaption></figure><p>An offline-first application allows its users to access all or part of its functionality without an internet connection. To provide this capability, we need two types of data sources:</p><ul><li><strong>Local Data Source:<br></strong>The only data that is always available comes from local storage. To support an offline-first approach, we cache data locally. The cache may reside in memory, a database, or another storage mechanism.</li><li><strong>Remote Data Source:<br></strong>Server data is required to populate local storage. Remote data sources are where the client fetches data from the server.</li></ul><blockquote>For any data retrieved from a remote source, we create a corresponding local data source to provide cached access. The local data source serves as the single source of truth regardless of internet connectivity.</blockquote><h4>Synchronization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*BEg8w1xqfm1GCUT4aUWH0A.png" /><figcaption>Two Common Synchronization Methods</figcaption></figure><p>To populate local storage with remote data, there are two common methods for an offline-first application to synchronize with server:</p><ul><li><strong>Pull-based Synchronization:</strong><br>The application requests the latest data on user demand. For example, a user can swipe to refresh the photo list in the GalleryFragment. This approach may not always present the most up-to-date data, since the timing of requests is not synchronized with server updates.</li><li><strong>Push-based Synchronization:<br></strong>In this method, the application uses push notifications to determine the exact timing for fetching data. Since notifications are sent from the server, the application knows precisely when the data is updated, reducing the likelihood of showing outdated information. However, this method is more complex to implement, as it requires integrating a push notification service.</li></ul><blockquote>Pull-based synchronization is simple to implement but risks missing server updates and showing stale data. For a more real-time experience, push-based synchronization can be used to fetch data immediately after remote updates.</blockquote><h4>Write Strategies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*OKv5dXhWpdgLVglJMJxUsA.png" /><figcaption>Lazy Write Strategy Overview</figcaption></figure><p>If your application allows its users to make changes, it will also need to upload the edited info. There are two common methods to handle this task:</p><ul><li><strong>Online-only Writes:</strong><br>In this approach, users can write data only when a network connection is available. The data is immediately sent to the server, which responds right after. It should be reserved only for critical operations because it blocks user interactions until the network responds.</li><li><strong>Lazy Writes:</strong><br>Writes are cached locally and uploaded once a network connection becomes available. Since users only wait for local I/O, this method does not interrupt interactions. However, it requires implementing local storage in a way that can track edited data for upload. If the data is also being pulled from the server, a conflict resolution strategy such as last-write-wins must be implemented.</li></ul><blockquote>Despite its added complexity, lazy writes are generally the best default strategy for offline-first applications. Online-only writes should be reserved for critical operations.</blockquote><h4>Task Scheduling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*7RK2lBc-4z3EBwU6cnW5KQ.png" /><figcaption>Pull-based Synchronization Scheduling</figcaption></figure><p>With pull-based synchronization, it is possible that a user may never trigger an update for a long time. It is generally unacceptable to display overly outdated data:</p><ul><li>To prevent this, we need to schedule periodic jobs that automatically fetch remote data. On Android, the <a href="https://developer.android.com/develop/background-work/background-tasks/persistent/getting-started">WorkManager</a> library provides the required functionalities for this task.</li><li>For lazy writes to work properly, we also need to handle network constraints. WorkManager supports this through <em>Constraints</em> which allows jobs to run only when conditions such as network availability are met.</li><li>By using task scheduling, I/O operations with the server are detached from the UI and can run independently.</li></ul><blockquote>If you want to build an offline-first application, WorkManager already supports network detection, periodic updates, and background execution independent of the UI.</blockquote><p>These patterns are also discussed in the official Android documentation. I’ll include the links here and cover the implementation in the next section.</p><ul><li><a href="https://developer.android.com/topic/architecture/data-layer/offline-first">Offline-first</a></li><li><a href="https://developer.android.com/develop/background-work/background-tasks/persistent">Task Scheduling</a></li></ul><h3>Implementation Details</h3><h4>Data Sources Integration</h4><pre>interface BookRepository {<br>    suspend fun fetchBooks()<br>    fun getBookListFlow(): Flow&lt;List&lt;BookDO&gt;&gt;<br>    suspend fun markAsFavorite(<br>        bookId: String, <br>        isFavorite: Boolean, <br>        updateTime: Long<br>    )<br>    suspend fun uploadFavoriteStatus()<br>}<br><br>class BookRepositoryImp(<br>    private val bookDao: BookDao,   // Local Database<br>    private val bookService: Book Service  // Remote API Client<br>): BookRepository {<br>    // Synchronization<br>    override suspend fun fetchBooks() {<br>        bookDao.upsert(bookService.fetchBooks().map {<br>            //...//<br>        })<br>    }<br><br>    // The Single Source of Truth of Books<br>    override fun getBookListFlow() = bookDao.getBookListFlow().map { <br>        //...//<br>    }<br><br>    // User Interaction Submission<br>    override suspend fun markAsFavorite(<br>        bookId: String, <br>        isFavorite: Boolean,<br>        updateTime: Long<br>    ) {<br>        bookDao.upsertLocalStatus(entity = LocalStatusEntity(<br>            bookId = bookId,<br>            isFavorite = isFavorite,<br>            updateTime = updateTime<br>        ))<br>    }<br><br>    // User Data Upload<br>    override suspend fun uploadFavoriteStatus() {<br>        val editedBooks = bookDao.getEditedBooks()<br><br>        bookService.uploadFavoriteStatuses(editedBooks.map {<br>            //...//<br>        })<br><br>        // Clear local statuses and update BookEntity list.<br>        bookDao.updateBooksWithLocalStatuses(editedBooks)<br>    }<br>}</pre><p>BookRepository integrates the local data source (BookDao) and the remote data source (BookService). Its data flow is the core of the offline-first pattern:</p><ul><li>There is no need to explicitly declare separate local and remote data source classes. The focus here is on how the data flows from the remote source to the local storage.</li><li>BookDao saves the books fetched by calling BookService.fetchBooks() and exposes the data through a Flow. Consumers only need to observe it to get the latest results.</li><li>BookDao also stores user edits for later uploads by calling BookDao.markAsFavorite(). When the internet is available, consumers can call uploadFavoriteStatuses() to send local changes to the server.</li><li>Thus, BookDao becomes the middle layer between the remote data and UI rendering, so the user interactions are not interrupted by the absence of connectivity.</li></ul><h4>Pull-based Synchronization</h4><pre>@Composable<br>fun BookListScreen(<br>    viewModel: BookListViewModel = viewModel()<br>) {<br>    val bookList by viewModel.bookListFlow.collectAsStateWithLifecycle()<br><br>    var isBookListFetched by remember{ mutableStateOf(false) }<br><br>    // Fetch books if it hasn’t been tried yet<br>    LaunchedEffect(isBookListFetched) {<br>        if (!isBookListFetched) {<br>            viewModel.fetchBooks()<br>            <br>            isBookListFetched = true<br>        }<br>    }<br><br>    // Render the books with the layout Composable<br>    BookListLayout(<br>        bookList = bookList,<br>        onRefresh = {<br>            // Trigger fetching by user interaction<br>            viewModel.fetchBooks()<br>        }<br>    )<br>}<br><br>@Composable<br>fun BookListLayout(<br>    bookList: List&lt;BookDO&gt;,<br>    onRefresh: () -&gt; Unit<br>) {<br>    //...//<br>}</pre><p>When the user navigates to BookListScreen, it triggers a call to fetch the latest books. This is a classic example of pull-based synchronization which is literally synchronization on demand:</p><ul><li>isBookListFetched is a flag used to track whether the fetch call has already been made for this screen.</li><li>The LaunchedEffect block is triggered only when the value of isBookListFetched changes.</li><li>When isBookListFetched is false, it triggers viewModel.fetchBooks() and then sets isBookListFetched to true.</li><li>BookListViewModel reflects the result by updating its bookListFlow, which in turn updates the UI.</li></ul><h4>Push-based Synchronization</h4><pre>@AndroidEntryPoint<br>class MyFCMService : FirebaseMessagingService() {<br>    @Inject<br>    lateinit var bookRepository: BookRepository<br><br>    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())<br><br>    private var fetchBookListJob: Job? = null<br><br>    override fun onMessageReceived(remoteMessage: RemoteMessage) {<br>        var isBookListUpdated = with(remoteMessage) {<br>            // Check if the book list has been updated on the server<br>            //...//<br>        }<br><br>        if (isBookListUpdated) {<br>            fetchBookListJob?.cancel()<br><br>            fetchBookListJob = serviceScope.launch {<br>                bookRepository.fetchBooks()<br>            }<br>        }<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        serviceScope.cancel()<br>    }<br>}</pre><p>When the book list is updated on the server, a notification is sent and received by clients to trigger fetching. In this case, we use <a href="https://firebase.google.com/docs/cloud-messaging/get-started?platform=android">Firebase Cloud Messaging</a>, and <a href="https://developer.android.com/training/dependency-injection/hilt-android">Hilt</a> for the example:</p><ul><li>BookRepository is injected into MyFCMService using Hilt to provide data access inside the service.</li><li>A CoroutineScope is created to invoke suspend functions. Since it is the root scope of the service, we don’t want a single exception to crash the entire scope, so we use a SupervisorJob.</li><li>In onMessageReceived(), we check whether the server has updated the book list. If it has, we invoke BookRepository.fetchBooks() to synchronize.</li><li>If your data is fetched by many users at the same time, consider applying a random delay before fetching to avoid traffic spikes.</li></ul><h4>Lazy Writes</h4><pre>@Composable<br>fun BookEditScreen(<br>    viewModel: BookEditViewModel = viewModel()<br>) {<br>    val book = viewModel.bookStateFlow.collectAsStateWithLifecycle()<br>    <br>    BookEditLayout(<br>        book = book,<br>        onMarkAsFavorite = { isMarked -&gt;<br>            // Change book status and mark it as edited.<br>            // This applies to local storage and is reflected immediately.<br>            viewModel.markAsFavorite(<br>                bookId = book.bookId, <br>                isMarked = isMarked,<br>                updateTime = System.currentTimeMillis()<br>            )<br>        }<br>    )<br>}<br><br>@Composable<br>fun BookEditLayout(<br>    book: BookDO,<br>    onMarkAsFavorite: (isMarked: Boolean) -&gt; Unit<br>) {<br>    //...//<br>}<br><br>@AndroidEntryPoint<br>class MyApp: Application() {<br>    @Inject<br>    lateinit var bookRepository: BookRepository<br><br>    private val appScope = CoroutineScope(Dispatchers.Main + SupervisorJob())<br><br>    private var uploadFavoriteStatusJob: Job? = null<br><br>    override onCreate() {<br>        super.onCreate()<br>        getSystemService(ConnectivityManager::class.java)<br>            .registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {<br><br>                //...//<br><br>                override fun onCapabilitiesChanged(network : Network, networkCapabilities : NetworkCapabilities) {<br>                    // Upload previously edited books to the server when network is available<br>                    if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) {<br>                        uploadFavoriteStatusJob?.cancel()<br><br>                        uploadFavoriteStatusJob = appScope.launch {<br>                            bookRepository.uploadFavoriteStatus()<br>                        }<br>                    }<br>                }<br><br>                //...//<br><br>            })<br>        <br>    }<br>}</pre><p>Lazy writes let the application cache user interactions without uploading immediately. Once connectivity is available, the changes are uploaded to the server in the background:</p><ul><li>BookEditViewModel.markAsFavorite() changes the favorite status of a book and marks it for later uploading.</li><li>In onCapabilitiesChanged(), we invoke BookRepository.uploadFavoriteStatus() to complete synchronization.</li><li>This example is intentionally simplified. In a real application, you might want to upload changes as soon as possible. We will cover the concern later with job scheduling mechanisms.</li></ul><h4>I/O Conflict Resolution</h4><pre>@Entity(primaryKeys = [Column.BOOK_ID])<br>data class BookEntity(<br>    @ColumnInfo(name = Column.BOOK_ID) val bookId: String,<br>    @ColumnInfo(name = Column.DESCRIPTION) val description: String,<br>    @ColumnInfo(name = Column.IS_FAVORITE) val isFavorite: Boolean,<br>    @ColumnInfo(name = Column.UPDATE_TIME) val updateTime: Long<br>)<br><br>@Entity(<br>    primaryKeys = [Column.BOOK_ID],<br>    foreignKeys = [ForeignKey(<br>        childColumns = [Column.BOOK_ID],<br>        entity = BookEntity::class,<br>        onDelete = ForeignKey.CASCADE,<br>        parentColumns = [Column.BOOK_ID]<br>    )]<br>)<br>data class LocalStatusEntity(<br>    @ColumnInfo(name = Column.BOOK_ID) val bookId: String,<br>    @ColumnInfo(name = Column.IS_FAVORITE) val isFavorite: Boolean,<br>    @ColumnInfo(name = Column.UPDATE_TIME) val updateTime: Long<br>)<br><br>@DatabaseView(<br>    &quot;WITH Temp AS( SELECT &quot; +<br>            &quot;BookEntity.${Column.BOOK_ID} AS ${Column.BOOK_ID}, &quot; +<br>            &quot;BookEntity.${Column.DESCRIPTION} AS ${Column.DESCRIPTION}, &quot; +<br>            &quot;CASE &quot; +<br>            &quot;WHEN LocalStatusEntity.${Column.UPDATE_TIME} IS NOT NULL AND &quot; +<br>            &quot;LocalStatusEntity.${Column.UPDATE_TIME} &gt; BookEntity.${Column.UPDATE_TIME} &quot; +<br>            &quot;THEN 1 ELSE 0 &quot; +<br>            &quot;END AS ${Column.IS_EDITED}, &quot; +<br>            &quot;LocalStatusEntity.${Column.IS_FAVORITE} AS ${Column.IS_LOCAL_FAVORITE}, &quot; +<br>            &quot;BookEntity.${Column.IS_FAVORITE} AS ${Column.IS_REMOTE_FAVORITE}, &quot; +<br>            &quot;LocalStatusEntity.${Column.UPDATE_TIME} AS ${Column.LOCAL_UPDATE_TIME}, &quot; +<br>            &quot;BookEntity.${Column.UPDATE_TIME} AS ${Column.REMOTE_UPDATE_TIME} &quot; +<br>            &quot;From BookEntity &quot; +<br>            &quot;LEFT JOIN LocalStatusEntity ON LocalStatusEntity.${Column.BOOK_ID} = BookEntity.${Column.BOOK_ID}&quot; +<br>    &quot;) &quot; +<br>            <br>    &quot;SELECT &quot; +<br>            &quot;Temp.${Column.BOOK_ID} AS ${Column.BOOK_ID}, &quot; +<br>            &quot;Temp.${Column.DESCRIPTION} AS ${Column.DESCRIPTION}, &quot; +<br>            &quot;Temp.${Column.IS_EDITED} AS ${Column.IS_EDITED}, &quot; +<br>            &quot;CASE &quot; +<br>            &quot;WHEN Temp.${Column.IS_EDITED} = 1 &quot; +<br>            &quot;THEN Temp.${Column.IS_LOCAL_FAVORITE} ELSE Temp.${Column.IS_REMOTE_FAVORITE} &quot; + <br>            &quot;END AS ${Column.IS_FAVORITE}, &quot; +<br>            &quot;CASE &quot; +<br>            &quot;WHEN Temp.${Column.IS_EDITED} = 1 &quot; +<br>            &quot;THEN Temp.${Column.LOCAL_UPDATE_TIME} ELSE Temp.${Column.REMOTE_UPDATE_TIME} &quot; +<br>            &quot;END AS ${Column.UPDATE_TIME} &quot; +<br>            &quot;FROM Temp&quot;<br>)<br>data class BookView(<br>    @ColumnInfo(name = Column.BOOK_ID) val bookId: String,<br>    @ColumnInfo(name = Column.DESCRIPTION) val description: String,<br>    @ColumnInfo(name = Column.IS_EDITED) val isEdited: Boolean,<br>    @ColumnInfo(name = Column.IS_FAVORITE) val isFavorite: Boolean,<br>    @ColumnInfo(name = Column.UPDATE_TIME) val updateTime: Long<br>)<br><br>interface BookDao {<br>    @Transaction<br>    fun updateBooksWithLocalStatuses(editedBooks: List&lt;BookView&gt;) {<br>        editedBooks.forEach {<br>            updateIsFavorite(<br>                bookId = it.bookId, <br>                isFavorite = it.isFavorite, <br>                updateTime = it.updateTime<br>            )<br><br>            clearLocalStatus(bookIds = it.bookId)<br>        }<br>    }<br><br>    @Query(&quot;DELETE FROM LocalStatusEntity WHERE ${Column.BOOK_ID} = :bookId&quot;)<br>    fun clearLocalStatus(bookId: String)<br><br>    @Query(&quot;SELECT * FROM BookView&quot;)<br>    fun getBookListFlow(): Flow&lt;List&lt;BookView&gt;&gt;<br><br>    @Query(&quot;SELECT * FROM BookView WHERE ${Column.IS_EDITED} = 1&quot;)<br>    fun getEditedBooks(): List&lt;BookView&gt;<br><br>    @Query(<br>        &quot;UPDATE BookEntity &quot; +<br>        &quot;SET ${Column.IS_FAVORITE} = :isFavorite, &quot; +<br>        &quot;${Column.UPDATE_TIME} = :updateTime &quot; +<br>        &quot;WHERE ${Column.BOOK_ID} = :bookId&quot;<br>    )<br>    fun updateIsFavorite(bookId: String, isFavorite: Boolean, updateTime: Long)<br><br>    @Upsert<br>    fun upsertBooks(entities: List&lt;BookEntity&gt;)<br><br>    @Upsert<br>    fun upsertLocalStatus(entity: LocalStatusEntity)<br>}</pre><p>Assuming the favorite status is also returned from the server to support multiple devices, it may conflict with local changes, so we implement a last-write-wins (LWW) mechanism to resolve conflicts:</p><ul><li>LocalStatusEntity stores user edits done locally.</li><li>When querying the book list, we compare UPDATE_TIME in BookEntity and LocalStatusEntity to determine which IS_FAVORITE value to use. It means the latest update wins.</li><li>The same comparison also determines whether the favorite status is edited locally. This allows querying for edited books that need to be uploaded.</li><li>After successfully uploading local edits, we clear the uploaded LocalStatusEntity entries and update BookEntity accordingly to prevent re-uploading.</li></ul><h4>Sync Task Scheduling</h4><pre>@HiltWorker<br>class BooksSyncWorker @AssistedInject constructor(<br>    @Assisted appContext: Context,<br>    @Assisted workerParams: WorkerParameters,<br>    private val bookRepository: BookRepository<br>): CoroutineWorker(appContext, workerParams) {<br>    override suspend fun doWork(): Result {<br>        return try {<br>            bookRepository.fetchBooks()<br>            <br>            Result.success()<br>        } catch (e: Exception) {<br>            if (e is CancellationException)<br>                throw e<br>            else<br>                Result.retry()<br>        }<br>    }<br><br>    companion object {<br>        fun Context.scheduleBooksSync() = <br>            WorkManager.getInstance(this).enqueueUniquePeriodicWork(<br>                uniqueWorkName = &quot;BooksSyncWorker&quot;,<br>                existingWorkPolicy = ExistingPeriodicWorkPolicy.KEEP,<br>                work = PeriodicWorkRequestBuilder&lt;BooksUploadWorker&gt;(<br>                    repeatInterval = 1, <br>                    repeatIntervalTimeUnit = TimeUnit.DAYS,<br>                    flexInterval = 12,<br>                    flexIntervalTimeUnit = TimeUnit.HOURS<br>                )<br>                .setConstraints(<br>                    Constraints.Builder()<br>                        .setRequiredNetworkType(NetworkType.CONNECTED)<br>                        .build()<br>                )<br>                .build()<br>            )<br>    }<br>}<br><br>@HiltAndroidApp<br>class ExampleApplication : Application(), Configuration.Provider {<br>    @Inject lateinit var workerFactory: HiltWorkerFactory<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        scheduleBooksSync()<br>    }<br><br>    override fun getWorkManagerConfiguration() =<br>        Configuration.Builder()<br>            .setWorkerFactory(workerFactory)<br>            .build()<br>}</pre><p>With WorkManager, it is simple to schedule a task to periodically refresh the local cache to keep data from becoming outdated:</p><ul><li>To access BookRepository in BooksSyncWorker, we use <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack#workmanager">Hilt integration</a> to inject the instance.</li><li>In doWork(), we call bookRepository.fetchBooks(). If the operation succeeds, we return Result.success(). If it fails, we can return Result.retry() by wrapping the call in a try-catch block.</li><li>Here, the job is scheduled to run once per day, with a flex interval of 12 hours. This flex interval helps mitigate traffic spikes when many users fetch data simultaneously.</li><li>The NetworkType.CONNECTED constraint ensures that the job only runs when the device has an internet connection. If the device is offline, the task will be pending and automatically executed once connectivity is restored.</li><li>This can work with the previous example shown in the pull-based synchronization section. Let users fetch the latest books on demand in the UI while the background worker keeps the cache reasonably up-to-date for future visits.</li></ul><h4>Upload Task Scheduling</h4><pre>@HiltWorker<br>class BooksUploadWorker @AssistedInject constructor(<br>    @Assisted appContext: Context,<br>    @Assisted workerParams: WorkerParameters,<br>    private val bookRepository: BookRepository<br>): CoroutineWorker(appContext, workerParams) {<br>    override suspend fun doWork(): Result {<br>        return try {<br>            bookRepository.uploadFavoriteStatus()<br>            <br>            Result.success()<br>        } catch (e: Exception) {<br>            if (e is CancellationException)<br>                throw e<br>            else<br>                Result.retry()<br>        }<br>    }<br><br>    companion object {<br>        fun Context.scheduleBooksUpload() = <br>            WorkManager.getInstance(this).enqueueUniqueWork(<br>                uniqueWorkName = &quot;BooksUploadWorker&quot;,<br>                existingWorkPolicy = ExistingWorkPolicy.REPLACE,<br>                work = OneTimeWorkRequestBuilder&lt;BooksUploadWorker&gt;()<br>                .setConstraints(<br>                    Constraints.Builder()<br>                        .setRequiredNetworkType(NetworkType.CONNECTED)<br>                        .build()<br>                )<br>                .build()<br>            )<br>    }<br>}<br><br>@Composable<br>fun BookEditScreen2(<br>    viewModel: BookEditViewModel = viewModel()<br>) {<br>    val actions = viewModel.stateFlow.map { it.actions }.collectAsStateWithLifecycle()<br>    val book = viewModel.bookStateFlow.collectAsStateWithLifecycle()<br>    val context = LocalContext.current<br><br>    LaunchedEffect(actions) {<br>        actions.forEach { action -&gt;<br>            when(action) {<br>                // Once the change is written to the local cache,<br>                // we can schedule the upload job, which will be executed when the internet is available.<br>                BookEditViewModel.State.Action.UploadFavoriteStatuses -&gt; <br>                    context.scheduleBooksUpload()<br>                    <br>            }<br>        }<br>    }<br>    <br>    BookEditLayout(<br>        book = book,<br>        onMarkAsFavorite = { isMarked -&gt;<br>            // Change book status and mark it as edited.<br>            // This applies to local storage and is reflected immediately.<br>            viewModel.markAsFavorite(<br>                bookId = book.bookId, <br>                isMarked = isMarked,<br>                updateTime = System.currentTimeMillis()<br>            )<br>        }<br>    )<br>}</pre><p>To support offline editing, we must ensure that changes are uploaded when the network is available. This can be achieved by using WorkManager with the NetworkType.CONNECTED constraint:</p><ul><li>scheduleBooksUpload() schedules a unique one-time work that replaces any previously pending job, ensuring that the latest data is always uploaded.</li><li>BookEditScreen2 triggers BookEditViewModel.State.Action.UploadFavoriteStatuses after finishing saving data to the local storage.</li><li>This ensures that whenever a change is made, there is always a pending task ready to upload the update.</li></ul><h3>Pros and Cons</h3><ul><li><strong>Pros:<br></strong>The main advantage of this pattern is that it eliminates most interruptions caused by network communication. The UI can observe local storage passively without manually updating values when server responses arrive.</li><li><strong>Cons:<br></strong>The mechanisms behind lazy writes and I/O conflict resolution are quite complex. While they offer clear benefits, they can be costly to implement.</li></ul><h3>Conclusion</h3><p>This experience comes from an e-book reader project where users can make notes. I was requested to support offline operations so that users could read books without connections. The offline-first pattern was a natural solution because there were many potential I/O conflicts across multiple devices per user. While the full mechanism may not be necessary for all applications, I still recommend making the local data source the single source of truth because it provides the most value at minimal cost.</p><ul><li><a href="https://github.com/Deathhit/SunflowerClone">GitHub - Deathhit/SunflowerClone: Android application architecture example composed of MVVM, UDF and modularization</a></li><li><a href="https://github.com/Deathhit/TaipeiTour/tree/master">GitHub - Deathhit/TaipeiTour: Android application architecture example composed of MVVM, UDF and modularization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=074727b13491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS-Style Database Schema: Write Optimized Tables and Read Only Views]]></title>
            <link>https://medium.com/@b9915034/cqrs-style-database-schema-write-optimized-tables-and-read-only-views-bfa89919a9a7?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa89919a9a7</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-patterns]]></category>
            <category><![CDATA[android-room-database]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[cqrs-pattern]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 07:01:33 GMT</pubDate>
            <atom:updated>2026-01-26T08:36:09.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*67P349wAclZ8xxjKo81nmw.png" /><figcaption>CQRS-Style Database Schema Overview</figcaption></figure><p>This article explores a CQRS-style schema design for SQL, where write operations use tables and reads rely on views for simplicity. Note: Edited in 2026/1/26.</p><h3>Introduction</h3><blockquote>How do you design database tables for complex requirements while keeping the schema simple?</blockquote><p>A SQL database is a convenient way to store large amounts of data for later queries. However, there is often a trade-off between making the schema read-friendly or write-friendly because normalization usually requires JOIN queries to obtain the desired data.</p><h3>Architectural Design Overview</h3><h4>CQRS Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*7YeMLCS4nOxY7v7nX7kZxA.png" /><figcaption>CQRS Separation of Write and Read</figcaption></figure><p>Command Query Responsibility Segregation (CQRS) is a design pattern that separates the responsibilities of read and write operations:</p><ul><li><strong>Command:</strong><br>Commands can be described as small business tasks that involve updating data. For example, you can add a plant to the garden planting list. They bridge user intentions with data changes.</li><li><strong>Query:<br></strong>Queries are operations that retrieve business state from data storage. For example, you can get a flow of plants from the database. These operations do not alter data.</li></ul><blockquote>CQRS divides data access into two categories: writes and reads. Designing a single table that performs well for both can be quite challenging.</blockquote><h4>Database View</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*5lRi8NR0HpSlemO7ig0QUQ.png" /><figcaption>Usage of Database View</figcaption></figure><p>A database view is a virtual table defined by a JOIN query that runs on one or more tables:</p><ul><li>You can create new queries based on database views without needing to know the schemas of the underlying tables.</li><li>Since a database view can represent a completely different model, it is well-suited for implementing read operations.</li></ul><blockquote>The segregation of commands and queries can be achieved by utilizing database views. A denormalized virtual table can be optimized for read operations, making it easier to normalize the real tables.</blockquote><h3>Implementation Details</h3><h4>Database Tables</h4><pre>@Entity(primaryKeys = [Column.PHOTO_ID])<br>data class PhotoEntity(<br>    @ColumnInfo(name = Column.AUTHOR_ID) val authorId: String,<br>    @ColumnInfo(name = Column.AUTHOR_NAME) val authorName: String,<br>    @ColumnInfo(name = Column.IMAGE_URL) val imageUrl: String,<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.PLANT_NAME) val plantName: String<br>)<br><br>@Entity(<br>    primaryKeys = [Column.PHOTO_ID],<br>    foreignKeys = [ForeignKey(<br>        childColumns = [Column.PHOTO_ID],<br>        entity = PhotoEntity::class,<br>        onDelete = ForeignKey.CASCADE,<br>        parentColumns = [Column.PHOTO_ID]<br>    )]<br>)<br>data class PhotoRemoteOrderEntity(<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.REMOTE_ORDER) val remoteOrder: Int<br>)</pre><ul><li>Tables should be normalized for write operations. In this case, two tables are separated based on their different data sources.</li><li>The properties of PhotoEntity map directly to API item properties, while PhotoRemoteOrderEntity represents the order of items in the response list.</li><li>If a new feature such as photo editing is required, another table can be specifically designed for it without interfering with existing structures.</li></ul><h4>Database Views</h4><pre>@DatabaseView(<br>    &quot;SELECT &quot; +<br>            &quot;PhotoEntity.${Column.AUTHOR_ID} AS ${Column.AUTHOR_ID}, &quot; +<br>            &quot;PhotoEntity.${Column.AUTHOR_NAME} AS ${Column.AUTHOR_NAME}, &quot; +<br>            &quot;PhotoEntity.${Column.IMAGE_URL} AS ${Column.IMAGE_URL}, &quot; +<br>            &quot;PhotoEntity.${Column.PHOTO_ID} AS ${Column.PHOTO_ID}, &quot; +<br>            &quot;PhotoEntity.${Column.PLANT_NAME} AS ${Column.PLANT_NAME}, &quot; +<br>            &quot;PhotoRemoteOrderEntity.${Column.REMOTE_ORDER} AS ${Column.REMOTE_ORDER} &quot; +<br>            &quot;FROM PhotoEntity &quot; +<br>            &quot;LEFT JOIN PhotoRemoteOrderEntity ON PhotoRemoteOrderEntity.${Column.PHOTO_ID} = PhotoEntity.${Column.PHOTO_ID}&quot;<br>)<br>data class PhotoItemView(<br>    @ColumnInfo(name = Column.AUTHOR_ID) val authorId: String,<br>    @ColumnInfo(name = Column.AUTHOR_NAME) val authorName: String,<br>    @ColumnInfo(name = Column.IMAGE_URL) val imageUrl: String,<br>    @ColumnInfo(name = Column.PHOTO_ID) val photoId: String,<br>    @ColumnInfo(name = Column.PLANT_NAME) val plantName: String,<br>    @ColumnInfo(name = Column.REMOTE_ORDER) val remoteOrder: Int?<br>)</pre><ul><li>To avoid the complexity of queries on normalized tables, we base our read operations on denormalized virtual tables.</li><li>PhotoItemView is a database view defined by a SELECT statement that joins PhotoEntity and PhotoRemoteOrderEntity.</li><li>This lets us query the photo list in the same order as the API response. It makes designing read operations more straightforward, since the database view already contains all the required information.</li></ul><h4>Data Access Objects</h4><pre>@Dao<br>interface PhotoDao {<br>    @Query(&quot;DELETE FROM PhotoEntity&quot;)<br>    suspend fun clear()<br><br>    @Query(&quot;SELECT * FROM PhotoRemoteKeysEntity WHERE :photoId = ${Column.PHOTO_ID}&quot;)<br>    suspend fun getRemoteKeys(photoId: String): PhotoRemoteKeysEntity?<br><br>    @Upsert<br>    suspend fun upsertPhoto(entities: List&lt;PhotoEntity&gt;)<br><br>    @Upsert<br>    suspend fun upsertRemoteKeys(entities: List&lt;PhotoRemoteKeysEntity&gt;)<br><br>    @Upsert<br>    suspend fun upsertRemoteOrder(entities: List&lt;PhotoRemoteOrderEntity&gt;)<br><br>    @Transaction<br>    suspend fun upsertPhotoPage(<br>        entities: List&lt;PhotoEntity&gt;,<br>        page: Int,<br>        pageSize: Int<br>    ) {<br>        //...//<br>    }<br>}<br><br>@Dao<br>interface PhotoItemDao {<br>    @Query(&quot;SELECT * FROM PhotoItemView WHERE :plantName = ${Column.PLANT_NAME} ORDER BY ${Column.REMOTE_ORDER} ASC&quot;)<br>    fun getEntitiesPagingSource(plantName: String): PagingSource&lt;Int, PhotoItemView&gt;<br>}</pre><ul><li>To comply with CQRS, we create one DAO for the entities and another for the database view.</li><li>DAOs of entities provide access to the commands. Statements here do not need to consider how the information will be retrieved later.</li><li>DAOs of views contain queries to read data, so they don’t need to include how the data is written.</li></ul><h4>Database</h4><pre>@Database(<br>    entities = [<br>        GardenPlantingEntity::class,<br>        PhotoEntity::class,<br>        PhotoRemoteKeysEntity::class,<br>        PhotoRemoteOrderEntity::class,<br>        PlantEntity::class<br>    ],<br>    version = 1,<br>    views = [<br>        GardenPlantingItemView::class,<br>        PhotoItemView::class,<br>        PlantItemView::class<br>    ]<br>)<br>abstract class SunflowerCloneDatabase : RoomDatabase() {<br>    abstract fun gardenPlantingDao(): GardenPlantingDao<br>    abstract fun gardenPlantingItemDao(): GardenPlantingItemDao<br>    abstract fun photoDao(): PhotoDao<br>    abstract fun photoItemDao(): PhotoItemDao<br>    abstract fun plantDao(): PlantDao<br>    abstract fun plantItemDao(): PlantItemDao<br>}</pre><ul><li>The implementation of the database itself does not change. You only need to remember to include the database view declarations in the @Database annotation.</li><li>One important thing is that you need to handle database migrations if a database view is modified. Room does support auto migrations. For example, to migrate from version 1 to version 2, you can include autoMigrations = [ AutoMigration(from = 1, to = 2) ] in the @Database annotation.</li></ul><h3>Pros, and Cons</h3><ul><li><strong>Pros:<br></strong>Denormalized views and normalized tables make designing SQL statements much easier. They are easier to understand because write and read operations are separated, and optimized.</li><li><strong>Cons:<br></strong>Creating database views requires extra boilerplate, and adds additional work to database design. Views also need to be migrated as your database evolves.</li></ul><h3>Conclusion</h3><p>The inspiration for this pattern came from my experience working with an API that was designed for the web instead of the Android application. This pattern helped me avoid polluting UI data with API mapping logic to keep the code clean. If you’re struggling with complex query requirements, adopting a CQRS-style schema may save you the headaches.</p><ul><li><a href="https://github.com/Deathhit/SunflowerClone">GitHub - Deathhit/SunflowerClone: Android application architecture example composed of MVVM, UDF and modularization</a></li><li><a href="https://github.com/Deathhit/TaipeiTour/tree/master">GitHub - Deathhit/TaipeiTour: Android application architecture example composed of MVVM, UDF and modularization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa89919a9a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM with Unidirectional Data Flow: Improving State Management]]></title>
            <link>https://medium.com/@b9915034/mvvm-with-unidirectional-data-flow-improving-state-management-651ae73b1fd1?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/651ae73b1fd1</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[unidirectional-data-flow]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mvi]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 09:27:54 GMT</pubDate>
            <atom:updated>2026-11-09T06:37:28.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Hno_QgZ5umpSDdhkzV96Aw.png" /><figcaption>MVVM with UDF Overview</figcaption></figure><p>In this article, we will explore how MVVM architecture can benefit by adopting UDF without inheriting the full complexity associated with MVI. Note: Edited in 2026/1/26.</p><h3>Introduction</h3><blockquote>How do you determine the color of a button if it depends on more than one observable in MVVM?</blockquote><p>MVVM is a presentation-level architecture where the view observes state from the view model and delegates user interactions back to it. As the UI grows in complexity, managing multiple observables becomes unwieldy.</p><h3>Architectural Design Overview</h3><h4>Unidirectional Data Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*SAezyYsaMK0tVgWxib-l_g.png" /><figcaption>Data Flow in One Direction</figcaption></figure><p>Unidirectional Data Flow (UDF) is a design pattern in which data moves through a screen in a single, predictable direction:</p><ul><li>MVI implements UDF by mapping user interactions to intent classes and exposing a single state that is transformed by reducing those intents.</li><li>The intents are handled by a reducer function in the view model which transforms the current state into a new one.</li><li>The UI observes and renders itself solely based on a single state from the view model which serves as the Single Source of Truth (SSOT).</li></ul><blockquote>The key difference between MVI and MVVM is that MVI adopts a Redux-like approach to enforce UDF. While this makes the single state object in MVI the SSOT, it often introduces more boilerplate and setup.</blockquote><h4>MVVM Adoption of UDF</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*LcVTdCLVJyCy6LuBVAOx-Q.png" /><figcaption>View Model Functions for Triggering State Transformations</figcaption></figure><p>Unlike MVI, MVVM does not inherently enforce UDF, but it can still adopt UDF principles without altering its fundamentals:</p><ul><li>UDF can be achieved in MVVM by consolidating all view model observables into a single state flow. The view then passively reacts to this unified state without observing multiple data flows.</li><li>Each view model function triggers a transformation of the current state, and acts as the intent equivalent in MVI. This still preserves the nature of UDF: user interaction → state transformation → UI update.</li></ul><blockquote>MVI enforces stricter unidirectional data flow compared to MVVM. By replacing explicit intents with view model functions, you can retain most of the benefits of MVI while reducing boilerplate.</blockquote><h4>VM Event Handling with UDF</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*qpP4uoRoLDZ3hLUCtMFSng.png" /><figcaption>Using an Additional Event Channel to Handle One Time Events</figcaption></figure><p>It is common practice to display a short-lived message to notify the user of the result of an API request. A usual way to achieve this is to introduce an additional flow as an event bus:</p><ul><li>Despite it is common practice, a view model event is actually a reflection of a state transition. An event that triggers a toast is expressing a change in state: the toast was not shown, and now it is.</li><li>Using a separate flow for one-time events splits the output of the view model into multiple pipelines. This separation undermines the SSOT principle because there are now two sources of view model state.</li><li>It’s fair to argue that using flags to track whether a one-time event has been handled introduces boilerplate, but there are implementation strategies to mitigate the problem.</li></ul><blockquote>While using an event channel may seem like a convenient solution for handling one-time actions, it actually splits the view model state into two flows and violates the SSOT principle.</blockquote><h4>Extra Flows for Foreign States</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*cEp5QQZxDBjgVotK04Y4Qw.png" /><figcaption>Two Independent States in MVVM UDF</figcaption></figure><p>In many cases, UI may also need to display data which originates from external sources:</p><ul><li>If you duplicate external data as part of the view model state, you’re effectively storing the same information in two places. The view model state should hold only the query parameters to derive a data state flow.</li><li>Take PlantDetailsViewModel.State as an example, it holds a plantId that identifies which PlantDO to display. The actual plant data should be retrieved from the repository using this plantId.</li><li>This can be done by applying flatMapLatest() to the view model state flow to derive a new data flow.</li></ul><blockquote>While exposing multiple flows from a view model may seem counterintuitive, it’s entirely valid because derived data from repositories is not part of the view model state.</blockquote><h3>Implementation Details</h3><h4>State Class</h4><pre>@Parcelize<br>data class State(<br>    val actions: List&lt;Action&gt; = emptyList(),<br>    val plantId: String<br>) : Parcelable {<br>    sealed interface Action : Parcelable {<br>        @Parcelize<br>        data object GoBack : Action<br><br>        @Parcelize<br>        data class GoToGalleryScreen(val plantName: String) : Action<br><br>        @Parcelize<br>        data class SharePlant(val plantName: String) : Action<br><br>        @Parcelize<br>        data class Toast(val type: ToastType) : Action<br>    }<br>}</pre><p><strong>Data Class for State Management:</strong></p><ul><li>A state class should be declared as a data class which enables the use of copy() to produce a new state with updated values.</li><li>When a user clicks on a tab to view filtered content, you can create a new state by copying the previous state and updating only the tab attribute. This avoids manually reassigning every property again and again.</li></ul><p><strong>Sealed Interface for State Transitions:</strong></p><ul><li>To clearly represent mutually exclusive UI states during transitions (such as loading, success, or failure), you can use a sealed interface as a property within your state class.</li><li>Each subtype encapsulates a distinct scenario, and since only one can exist at a time, this makes the state handling more safe.</li></ul><p><strong>List and Sealed Interface for One-Time Events:</strong></p><ul><li>One-time events can represent navigation triggers, toasts, and something else.</li><li>A straightforward approach is to use Boolean or nullable values that are reset after handling, but this can bloat the state class with flags.</li><li>It is better to define a sealed interface to represent the events, maintain a list of it, and remove it from the list to complete the lifecycle.</li></ul><p><strong>Parcelable Implementation for State Restoration:</strong></p><ul><li>To support state restoration after process death, a state class should implement Parcelable to allow it to be saved in the SavedStateHandle.</li><li>Kotlin Parcelize plugin simplifies this by generating the Parcelable implementation automatically.</li></ul><h4>View Model</h4><pre>@HiltViewModel<br>class PlantDetailsViewModel @Inject constructor(<br>    private val gardenPlantingRepository: GardenPlantingRepository,<br>    private val plantRepository: PlantRepository,<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    private val _stateFlow: MutableStateFlow&lt;State&gt; = savedStateHandle.getMutableStateFlow(<br>        KEY_STATE, <br>        savedStateHandle[KEY_STATE]!!<br>    )<br>    val stateFlow: StateFlow&lt;State&gt; = _stateFlow.asStateFlow()<br><br>    val plantFlow =<br>        createPlantFlow().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)<br><br>    private var addPlantJob: Job? = null<br>    private var goToGalleryJob: Job? = null<br>    private var sharePlantJob: Job? = null<br><br>    fun addPlantToGarden() {<br>        addPlantJob?.cancel()<br><br>        addPlantJob = viewModelScope.launch {<br>            gardenPlantingRepository.addGardenPlanting(plantId = stateFlow.value.plantId)<br><br>            _stateFlow.update { it.copy(actions = it.actions + State.Action.Toast(ToastType.AddedPlantToGarden)) }<br>        }<br>    }<br><br>    fun goBack() {<br>        _stateFlow.update { it.copy(actions = it.actions + State.Action.GoBack) }<br>    }<br><br>    fun goToGalleryScreen() {<br>        goToGalleryJob?.cancel()<br><br>        goToGalleryJob = viewModelScope.launch {<br>            val plant = createPlantFlow().first() ?: return@launch<br><br>            _stateFlow.update { <br>                it.copy(<br>                    actions = it.actions + State.Action.GoToGalleryScreen(<br>                        plantName = plant.plantName<br>                    )<br>                )<br>            }<br>        }<br>    }<br><br>    fun onAction(action: State.Action) {<br>        _stateFlow.update { it.copy(actions = it.actions - action) }<br>    }<br><br>    fun sharePlant() {<br>        sharePlantJob?.cancel()<br><br>        sharePlantJob = viewModelScope.launch {<br>            val plant = createPlantFlow().first() ?: return@launch<br><br>            _stateFlow.update {<br>                it.copy(actions = it.actions + State.Action.SharePlant(plantName = plant.plantName))<br>            }<br>        }<br>    }<br><br>    private fun createPlantFlow() = stateFlow.map { it.plantId }.flatMapLatest {<br>        plantRepository.getPlantFlow(it)<br>    }<br><br>    companion object {<br>        private const val TAG = &quot;PlantDetailsViewModel&quot;<br>        private const val KEY_STATE = &quot;$TAG.KEY_STATE&quot;<br><br>        internal fun createArgs(plantId: String) = Bundle().apply {<br>            putParcelable(<br>                KEY_STATE, State(<br>                    plantId = plantId<br>                )<br>            )<br>        }<br>    }<br>}</pre><p><strong>State Flow:</strong></p><ul><li><strong>State Immutability:<br></strong>UI shouldn’t be allowed to modify a view model state by itself to ensure data consistency. A common pattern is to declare a MutableStateFlow internally and exposes it as a StateFlow using asStateFlow(). This ensures that the view can observe the state but cannot modify it directly.</li><li><strong>State Persistence: </strong><br>To persist the state across process death, you should synchronize the state with a SavedStateHandle. This can be streamlined by defining a delegate for the MutableStateFlow. The delegate’s setter should update the MutableStateFlow and also save the new value to the SavedStateHandle.</li></ul><p><strong>Intent Functions:</strong></p><ul><li><strong>Naming:<br></strong>Function names should clearly express the intent behind their invocation. If the UI triggers navigation from a NavigationFragment to a PlantDetailsFragment, the function in NavigationViewModel could be named goToPlantDetailsScreen().</li><li><strong>Cancelation:</strong><br>When a function performs asynchronous work, consider cancelling any previous work to prevent race conditions. This can be achieved by maintaining a reference to the coroutine Job, and cancelling it before launching a new one.</li><li><strong>Synchronization:</strong><br>View model functions should be safe to call from the main thread. Asynchronous operations should be handled internally using viewModelScope to ensure proper coroutine lifecycle management. Avoid declaring intent functions as suspend.</li></ul><p><strong>Constructor:</strong></p><ul><li><strong>Initial State:</strong><br>We can use SavedStateHandle to initialize the state by retrieving data from a Bundle. It can originate from the arguments of a Fragment, the Intent extras, or navigation parameters if you&#39;re using Jetpack Compose Navigation. SavedStateHandle is also used to persist the current state, and restore it when the view model is recreated.</li><li><strong>Repositories and Use Cases:</strong><br>In many cases, the view model state alone is not sufficient to render the UI. Therefore, repositories and use cases are injected into the constructor to access the required data sources.</li></ul><p><strong>External Data Flow:</strong></p><ul><li><strong>View Model State as Query:</strong><br>You should store the query parameters as part of the view model state, and use the flatMapLatest() operator to transform the state flow into a new flow that emits filtered external data.</li><li><strong>Cold Flow to Hot State Flow:<br></strong>Repositories often emit cold flows, and can lead to a gap where no value is available during the initial loading phase. To address the issue, you can use the stateIn() operator to convert a cold Flow into a hot StateFlow, allowing to provide an initial value.</li></ul><h4>View</h4><pre>@AndroidEntryPoint<br>class PlantDetailsFragment : Fragment() {<br>    var callback: Callback? = null<br><br>    private val binding get() = _binding!!<br>    private var _binding: FragmentPlantDetailsBinding? = null<br><br>    private val viewModel: PlantDetailsViewModel by viewModels()<br><br>    private val onAddPlantToGardenListener = View.OnClickListener {<br>        viewModel.addPlantToGarden()<br>    }<br>    private val onGoBackListener = View.OnClickListener {<br>        viewModel.goBack()<br>    }<br>    private val onGoToGalleryScreenListener = View.OnClickListener {<br>        viewModel.goToGalleryScreen()<br>    }<br>    private val onClickMenuItemListener = Toolbar.OnMenuItemClickListener { item -&gt;<br>        when (item.itemId) {<br>            R.id.action_share -&gt; {<br>                viewModel.sharePlant()<br><br>                true<br>            }<br><br>            else -&gt; false<br>        }<br>    }<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater,<br>        container: ViewGroup?,<br>        savedInstanceState: Bundle?<br>    ): View =<br>        FragmentPlantDetailsBinding.inflate(inflater, container, false).also { _binding = it }.root<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        with(binding.textViewDescription) {<br>            movementMethod = LinkMovementMethod.getInstance()<br>        }<br><br>        configureEdgeToEdge()<br><br>        bindViewModelState()<br>    }<br><br>    override fun onResume() {<br>        super.onResume()<br>        with(binding) {<br>            fab.setOnClickListener(onAddPlantToGardenListener)<br>            imageViewGoToGallery.setOnClickListener(onGoToGalleryScreenListener)<br>            toolbar.setNavigationOnClickListener(onGoBackListener)<br>            toolbar.setOnMenuItemClickListener(onClickMenuItemListener)<br>        }<br>    }<br><br>    override fun onPause() {<br>        super.onPause()<br>        with(binding) {<br>            fab.setOnClickListener(null)<br>            imageViewGoToGallery.setOnClickListener(null)<br>            toolbar.setNavigationOnClickListener(null)<br>            toolbar.setOnMenuItemClickListener(null)<br>        }<br>    }<br><br>    override fun onDestroyView() {<br>        super.onDestroyView()<br>        _binding = null<br>    }<br><br>    private fun bindViewModelState() {<br>        viewLifecycleOwner.lifecycleScope.launch {<br>            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                launch {<br>                    viewModel.stateFlow.map { it.actions }.distinctUntilChanged()<br>                        .collectLatest { actions -&gt;<br>                            actions.forEach { action -&gt;<br>                                sequenceOf(<br>                                    when (action) {<br>                                        is PlantDetailsViewModel.State.Action.GoBack -&gt; callback?.onGoBack()<br>                                        is PlantDetailsViewModel.State.Action.GoToGalleryScreen -&gt; callback?.onGoToGalleryScreen(<br>                                            plantName = action.plantName<br>                                        )<br><br>                                        is PlantDetailsViewModel.State.Action.SharePlant -&gt; sharePlant(<br>                                            plantName = action.plantName<br>                                        )<br><br>                                        is PlantDetailsViewModel.State.Action.Toast -&gt; Toast.makeText(<br>                                            requireContext(),<br>                                            action.type.getMessage(requireContext()),<br>                                            Toast.LENGTH_LONG<br>                                        ).show()<br>                                    }<br>                                )<br><br>                                viewModel.onAction(action)<br>                            }<br>                        }<br>                }<br><br>                launch {<br>                    viewModel.plantFlow.filterNotNull().distinctUntilChanged()<br>                        .collectLatest { plant -&gt;<br>                            with(binding) {<br>                                fab.isVisible = !plant.isPlanted<br>                                imageViewPlant.let {<br>                                    Glide.with(it).load(plant.imageUrl).into(it)<br>                                }<br>                                textViewDescription.text = Html.fromHtml(<br>                                    plant.description,<br>                                    Html.FROM_HTML_MODE_LEGACY<br>                                )<br>                                textViewTitle.text = plant.plantName<br>                                textViewWateringValue.text = getString(<br>                                    R.string.plant_details_every_x_days,<br>                                    plant.wateringIntervalDays<br>                                )<br>                                toolbarLayout.title = plant.plantName<br>                            }<br>                        }<br>                }<br>            }<br>        }<br>    }<br><br>    private fun configureEdgeToEdge() {<br>        ViewCompat.setOnApplyWindowInsetsListener(requireView()) { root, windowInsets -&gt;<br>            val insets = windowInsets.getInsets(<br>                WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()<br>            )<br><br>            binding.nestedScrollView.updatePadding(<br>                bottom = insets.bottom,<br>                left = insets.left,<br>                right = insets.right<br>            )<br><br>            binding.appBarLayout.updatePadding(<br>                left = insets.left,<br>                right = insets.right,<br>                top = insets.top<br>            )<br><br>            WindowInsetsCompat.CONSUMED<br>        }<br>    }<br><br>    private fun sharePlant(plantName: String) {<br>        startActivity(<br>            ShareCompat.IntentBuilder(requireContext())<br>                .setText(getString(R.string.plant_details_share_message_x, plantName))<br>                .setType(&quot;text/plain&quot;)<br>                .createChooserIntent()<br>                .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)<br>        )<br>    }<br><br>    companion object {<br>        fun create(plantId: String) = PlantDetailsFragment().apply {<br>            arguments = createArgs(plantId = plantId)<br>        }<br><br>        fun createArgs(plantId: String) = PlantDetailsViewModel.createArgs(plantId = plantId)<br>    }<br><br>    interface Callback {<br>        fun onGoBack()<br>        fun onGoToGalleryScreen(plantName: String)<br>    }<br>}</pre><p><strong>Navigation Parameters:</strong></p><ul><li><strong>Parameters for Activity as Controller</strong>:<br>Use intent.putExtra() to pass parameters when launching the Activity.</li><li><strong>Parameters for Fragment without Jetpack Navigation</strong>:<br>Pass a Bundle containing the parameters and set it using fragment.setArguments().</li><li><strong>Parameters for Fragment with Jetpack Navigation</strong>:<br>Also use a Bundle, but provide it directly when calling navigate().</li><li><strong>Parameters for Jetpack Compose Navigation</strong>:<br>Encode parameters into the navigation route string, and pass the string to navigate().</li><li><strong>Parameter Access:</strong><br>All these values are accessed through the SavedStateHandle within the view model.</li></ul><p><strong>View Model Creation:</strong></p><ul><li><strong>View Model in Activity or Fragment:</strong><br>Use the viewModels() extension to obtain the view model scoped to the controller.</li><li><strong>View Model in Jetpack Compose Navigation:</strong><br>Use hiltViewModel() to retrieve the view model for a destination. If you’re using Koin instead of Hilt for DI, use koinViewModel() instead.</li><li><strong>One View Model per Controller:</strong><br>It is recommended to maintain a one-to-one relationship between a view and its view model. Avoid sharing view models across multiple views, such as using activityViewModels() in a Fragment. This ensures that the view model state is not altered by multiple views.</li></ul><p><strong>State Observations:</strong></p><ul><li><strong>XML UI Rendering:</strong><br>You should avoid re-rendering the entire UI whenever the state changes. Use map() on the StateFlow to derive smaller flows representing individual state properties. These can be collected independently to update specific parts of the UI.</li><li><strong>Compose UI rendering:</strong><br>Split Composable functions according to the parameters they need. Compose will automatically trigger composition only when those parameters change.</li><li><strong>Lifecycle Awareness:</strong><br>Unlike LiveData, Flow is not lifecycle-aware by default. You should launch collection in viewLifecycleOwner.lifecycleScope.launch {} and use viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {} to ensure that state is collected only when the view is active. If this is in an Activity, you can use lifecycleScope without viewLifecycleOwner.</li><li><strong>Collecting Individual Properties:</strong><br>If you need to collect parts of the state independently, wrap each collect {} block in a separate launch {}. This is necessary because collect {} is a blocking operation, and it won&#39;t return until the flow completes.</li><li><strong>Compose Lifecycle Awareness:<br></strong>You can collect a StateFlow inside a Composable by using collectAsState(). If lifecycle awareness is required, use collectAsStateWithLifecycle() instead.</li></ul><h4>Compose Controller-Layout Separation</h4><pre>@Composable<br>fun PlantDetailsScreen(<br>    onGoBack: () -&gt; Unit,<br>    onGoToGalleryScreen: (plantName: String) -&gt; Unit,<br>    viewModel: PlantDetailsViewModel = hiltViewModel()<br>) {<br>    val context = LocalContext.current<br><br>    val actions = viewModel.stateFlow.collectAsState().value.actions<br><br>    LaunchedEffect(actions) {<br>        actions.forEach { action -&gt;<br>            when (action) {<br>                PlantDetailsViewModel.State.Action.GoBack -&gt; onGoBack()<br>                is PlantDetailsViewModel.State.Action.GoToGalleryScreen -&gt; onGoToGalleryScreen(<br>                    action.plantName<br>                )<br><br>                is PlantDetailsViewModel.State.Action.SharePlant -&gt; sharePlant(<br>                    context = context,<br>                    plantName = action.plantName<br>                )<br><br>                is PlantDetailsViewModel.State.Action.Toast -&gt; showToast(<br>                    context = context,<br>                    msg = action.type.getMessage(context)<br>                )<br>            }<br><br>            viewModel.onAction(action)<br>        }<br>    }<br><br>    viewModel.plantFlow.collectAsState().value?.run {<br>        PlantDetailsLayout(<br>            description = description,<br>            isPlanted = isPlanted,<br>            plantImageUrl = imageUrl,<br>            plantName = plantName,<br>            wateringInterval = wateringIntervalDays,<br>            onBackClick = { viewModel.goBack() },<br>            onFabClick = { viewModel.addPlantToGarden() },<br>            onGalleryClick = { viewModel.goToGalleryScreen() },<br>            onShareClick = { viewModel.sharePlant() }<br>        )<br>    } ?: run {<br>        Box(modifier = Modifier.fillMaxSize())<br>    }<br>}<br><br>//...//<br><br>@Composable<br>fun PlantDetailsLayout(<br>    description: String,<br>    isPlanted: Boolean,<br>    plantImageUrl: String,<br>    plantName: String,<br>    wateringInterval: Int,<br>    onBackClick: () -&gt; Unit,<br>    onFabClick: () -&gt; Unit,<br>    onGalleryClick: () -&gt; Unit,<br>    onShareClick: () -&gt; Unit<br>) {<br><br>  //...//<br><br>}<br><br>@Preview<br>@Composable<br>private fun PlantDetailsPreview() {<br>    val context = LocalContext.current<br>    val toast = Toast.makeText(context, &quot;&quot;, Toast.LENGTH_LONG)<br><br>    SunflowerCloneTheme {<br>        PlantDetailsLayout(<br>            description = &quot;The tomato is the edible, often red, berry of the nightshade Solanum lycopersicum, commonly known as a tomato plant. The species originated in western South America. The Nahuatl (Aztec language) word tomatl gave rise to the Spanish word tomate, from which the English word tomato derived. Its use as a cultivated food may have originated with the indigenous peoples of Mexico. The Spanish encountered the tomato from their contact with the Aztec during the Spanish colonization of the Americas and brought it to Europe. From there, the tomato was introduced to other parts of the European-colonized world during the 16th century.&lt;br&gt;&lt;br&gt;The tomato is consumed in diverse ways, raw or cooked, in many dishes, sauces, salads, and drinks. While tomatoes are fruits – botanically classified as berries – they are commonly used as a vegetable ingredient or side dish.&lt;br&gt;&lt;br&gt;Numerous varieties of the tomato plant are widely grown in temperate climates across the world, with greenhouses allowing for the production of tomatoes throughout all seasons of the year. Tomato plants typically grow to 1–3 meters (3–10 ft) in height. They are vines that have a weak stem that sprawls and typically needs support. Indeterminate tomato plants are perennials in their native habitat, but are cultivated as annuals. Determinate, or bush, plants are annuals that stop growing at a certain height and produce a crop all at once. The size of the tomato varies according to the cultivar, with a range of 0.5–4 inches (1.3–10.2 cm) in width.&lt;br&gt;&lt;br&gt;(From &lt;a href=\&quot;https://en.wikipedia.org/wiki/Tomato\&quot;&gt;Wikipedia&lt;/a&gt;)&quot;,<br>            isPlanted = false,<br>            plantImageUrl = &quot;&quot;,<br>            plantName = &quot;Tomato&quot;,<br>            wateringInterval = 4,<br>            onBackClick = {<br>                toast.apply { setText(&quot;Clicked Back!&quot;) }.show()<br>            },<br>            onFabClick = {<br>                toast.apply { setText(&quot;Clicked Fab!&quot;) }.show()<br>            },<br>            onGalleryClick = {<br>                toast.apply { setText(&quot;Clicked Gallery!&quot;) }.show()<br>            },<br>            onShareClick = {<br>                toast.apply { setText(&quot;Clicked Share!&quot;) }.show()<br>            }<br>        )<br>    }<br>}</pre><ul><li><strong>Separation of Concerns:</strong><br>It is generally the best practice to separate view into at least two Composable functions for one acting as the controller and the other as the pure layout.</li><li><strong>Layout Preview Compatibility:</strong><br>Composable functions that take a ViewModel as a parameter cannot be previewed using the Preview annotation. Separating the layout into a stateless Composable enables design previews.</li><li><strong>Local State Management:<br></strong>A dedicated controller Composable can encapsulate local UI state (e.g., using remember and mutableStateOf()) without needing to pass parameters through the Composable hierarchy. It can also observe, and react to ViewModel state, bridging business logic and UI updates.</li></ul><h4>Delivering UI Events Across Fragments</h4><pre>@AndroidEntryPoint<br>class NavigationFragment : Fragment() {<br><br>    //...//<br><br>    private val viewModel: NavigationViewModel by viewModels()<br><br>    //...//<br><br>    override fun onAttach(context: Context) {<br>        super.onAttach(context)<br>        configureFragmentCallbacks()<br>    }<br><br>    //...//<br><br>    private fun configureFragmentCallbacks() {<br>        childFragmentManager.addFragmentOnAttachListener { _, fragment -&gt;<br>            when (fragment) {<br>                is GardenPlantingListFragment -&gt; fragment.callback =<br>                    object : GardenPlantingListFragment.Callback {<br>                        override fun onGoToPlantDetailsScreen(plantId: String) {<br>                            viewModel.goToPlantDetailsScreen(plantId)<br>                        }<br>                    }<br><br>                is PlantListFragment -&gt; fragment.callback = object : PlantListFragment.Callback {<br>                    override fun onGoToPlantDetailsScreen(plantId: String) {<br>                        viewModel.goToPlantDetailsScreen(plantId)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    //...//<br><br>}</pre><ul><li><strong>Lifecycle Problem:</strong><br>When communicating between Fragments, it is common to use a shared ViewModel which is scoped to the Activity. It can introduce complexity because an activity-scoped ViewModel can outlive both the Fragments.</li><li><strong>Parent-Child Communication:</strong><br>A cleaner approach is to define a callback interface in the child and let the parent implement it. You can pass this callback during the Fragment attachment phase by using fragmentManager.addFragmentOnAttachListener() to provide the callback at that time.</li><li><strong>One-Time Event Triggers:</strong><br>Triggering a callback is effectively a one-time UI event. If you need to share state (not just events) across Fragments, both the parent and child should maintain their own state instances. If such state can be provided from repositories instead, it should be the better approach.</li></ul><h3>Pros, Cons, and Discussion</h3><h4>Pros of MVVM with UDF</h4><ol><li><strong>Improved Testability:<br></strong>Compared to traditional MVVM, testing in MVVM with UDF is simpler because you only need to verify changes to a single state object. Having a centralized observable makes assertions more straightforward than observing multiple independent properties.</li><li><strong>Reduced Boilerplate:<br></strong>Traditional MVVM often requires declaring multiple observable properties in the view model. MVI centralizes state but introduces extra boilerplate through intent classes and reducers. MVVM with UDF strikes a balance by using a single state and intent functions.</li><li><strong>Simpler State Restoration:</strong><br>In the event of process death, MVVM with UDF simplifies state restoration because there is only a single state object to restore. Unlike traditional MVVM which often manages multiple properties, UDF centralizes all into one object. This reduces the complexity of saving and restoring individual fields.</li><li><strong>State Snapshot Consistency:<br></strong>MVVM observables can emit updates independently. When one observable notifies the UI, other properties may change concurrently. This can result in race conditions if the UI reacts to inconsistent data. In contrast, MVVM with UDF can provide atomic snapshots to ensure consistency.</li></ol><h4>Cons of MVVM with UDF</h4><ol><li><strong>Less Trackable UI Intent Flow:<br></strong>Compared to MVI where all user intents are funneled through a single reducer function, MVVM with UDF handles intents in separate functions. This can make it harder to log the full intent-to-state transition flow unless you explicitly deal with each function.</li><li><strong>Constant Object Creation:<br></strong>Each state update involves creating a new instance of the state object to maintain immutability. It can introduce performance overhead in scenarios with frequent updates, but it is usually ignorable.</li></ol><h3>Conclusion</h3><p>MVVM with UDF offers a cost-efficient alternative to MVI and a significant improvement over the traditional MVVM. It enables clearer state management with minimal boilerplate. This strikes a balance between structure and simplicity, and makes it a good default architecture.</p><ul><li><a href="https://github.com/Deathhit/SunflowerClone">GitHub - Deathhit/SunflowerClone: Android application architecture example composed of MVVM, UDF and modularization</a></li><li><a href="https://github.com/Deathhit/TaipeiTour/tree/master">GitHub - Deathhit/TaipeiTour: Android application architecture example composed of MVVM, UDF and modularization</a></li></ul><p><a href="https://codeberg.org/zerg_1111/LMA_Samples">https://codeberg.org/zerg_1111/LMA_Samples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=651ae73b1fd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layered Modular Architecture: Evolving Clean Architecture to Support Multiplatform Development]]></title>
            <link>https://medium.com/@b9915034/android-application-architecture-showcase-sunflower-clone-dee729f6e1f2?source=rss-fc8bc3133fb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dee729f6e1f2</guid>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[zerg 1111]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 11:12:21 GMT</pubDate>
            <atom:updated>2026-11-09T06:35:37.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*AxgxcVsS9A5EkXiwGAqo2A.png" /><figcaption>Layered Modular Architecture Overview</figcaption></figure><p>This article introduces the Layered Modular Architecture(LMA) with the <a href="https://github.com/Deathhit/SunflowerClone"><strong>Sunflower Clone</strong></a> project. Note: Edited in 2026/11/4.</p><p><strong>Disclaimer:</strong> <br>This is not an entirely new architecture but an extension of Clean Architecture. It introduces new concepts, and a revised modularization strategy, so I give it a new name to distinguish from the rest.</p><h3>Introduction</h3><blockquote>What architecture is best suited for multiplatform development?</blockquote><p>Multiplatform development is receiving increasing attention as Kotlin Multiplatform grows in popularity. Despite the maturity of KMP, an architecture that optimizes cross-platform code sharing is still desired. With Clean Architecture as the foundation, we will explore a better approach for multiplatform development.</p><h3>Overview</h3><h4>Challenges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*OJyXSLCW3eZAA6ZGJ3hSKw.png" /><figcaption>Illustration of the Classic Clean Architecture Implementation</figcaption></figure><p>Clean Architecture implementations on Android often utilize the data-domain-presentation structure with feature-based modularization:</p><ul><li>In multiplatform development, the objective is to maximize the amount of platform-independent code that can be shared across platforms.</li><li>Kotlin Multiplatform (KMP) does support dividing code for each platform, but the way how you do it is still a problem.</li><li>The traditional approach shown in the illustration results in a mixture of platform-independent code (Domain) and platform-dependent code (Data and Presentation).</li><li>Reusing common logic forces you to pull in the entire feature which creates dependency chains that break independent reusability.</li><li>Layered Modular Architecture (LMA) addresses this issue by separating platform-independent and platform-dependent concerns into independent layers and modules.</li></ul><blockquote>LMA is built on the foundations of Clean Architecture with easier code reuse as its primary goal. This maximizes the value of multiplatform development by increasing the amount of platform-independent code that can be shared.</blockquote><h4>Layered Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*UaAa3j-OgY71kjKRYmWSMQ.png" /><figcaption>Five Layers of Layered Modular Architecture</figcaption></figure><p>LMA establishes layers first in contrast to feature-based modularization. The five-layer architecture is specifically designed to enable patterns that improve code sharing:</p><ul><li><strong>Core Layer:</strong> <br>The core layer is responsible for hosting infrastructure that is independent of the business domain.</li><li><strong>Domain Layer:</strong> <br>The domain layer contains entities, repository interfaces, and use cases that represent the business logic. By not being tangled with other layers in the same module, it becomes a platform-independent layer.</li><li><strong>Data Layer:</strong> <br>The data layer contains implementations of the repository interfaces which integrate data sources to supply domain entities.</li><li><strong>Feature Layer:</strong> <br>The feature layer is responsible for hosting functionality centered around user interactions and visual representations.</li><li><strong>App Layer:</strong> <br>The app layer contains the application entry points which handle top-level concerns such as dependency injection, navigation, and coordination.</li></ul><blockquote>By moving layers outside of a single module, we can keep the layers independent of features which may be platform-dependent. These five layers establish a foundation to further decouple platform-independent logic.</blockquote><h4>Modularization in Layers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*cmDieS-95shIsPCilZysWg.png" /><figcaption>Modularization in Sunflower Clone</figcaption></figure><p>The layers other than the domain layer still contain both platform-independent and platform-dependent implementations:</p><ul><li>Instead of splitting the entire codebase into features, we can modularize each layer into “layer-features”.</li><li>If the domain layer contains three repository interfaces which are PlantRepository, PhotoRepository, and GardenPlantingRepository. We can divide the data layer based on these by creating modules like :data:plant, :data:photo, and :data:garden_planting. Each module implements one of the interfaces.</li><li>If PlantRepository needs to be accessible on both Android and iOS platforms, we can further divide :data:plant to provide specific implementations. This logical separation aligns well with KMP modules.</li><li>It is important to recognize that each layer has its own domain, and dividing modules based solely on vertical features can result in duplication.</li></ul><blockquote>Applying feature-based modularization to layers allows us to isolate platform-independent logic while enabling the creation of highly reusable, feature-specific components within each layer.</blockquote><h4>Dependency Inversion Principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*RQfhxsjxuAwxV50ihiX_Sw.png" /><figcaption>Dependency Inversion in Layered Modular Architecture</figcaption></figure><p>A feature may be platform-dependent only because the data it depends on is platform-dependent:</p><ul><li>The Dependency Inversion Principle (DIP) states that high-level modules should not depend directly on low-level modules.</li><li>In the context of LMA, the domain layer acts as the shared interfaces between feature and data layers.</li><li>The app layer injects the required data implementations of domain to satisfy feature requirements, so the features are decoupled from the data instead of direct dependency.</li><li>For example, :feature:plant_list does not depend on :data:plant. Instead, both depend on :domain. The :app:sunflower_clone module references :data:plant and injects PlantRepositoryImp as the PlantRepository instance used by :feature:plant_list.</li><li>This allows us to have platform-independent features with the capability to choose whatever data implementations we need for different platforms.</li></ul><blockquote>DIP decouples data and features by using the domain layer as a contract. This not only addresses platform-specific coupling but also allows the UI to be reused independently as long as the data contract is satisfied.</blockquote><h4>Coordinator Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*fGdjCjHwmJnPj7eVXbvC_g.png" /><figcaption>App Module Coordinating the Feature Modules in Sunflower Clone</figcaption></figure><p>Features can form a long dependency chain because navigation requires the knowledge of destination:</p><ul><li>The Coordinator Pattern suggests that a host should manage the navigation rather than allowing each destination to handle its own.</li><li>To address the coupling issue, the app layer serves as the coordinator, and handles the navigation logic for feature modules.</li><li>For example, NavigationFragment from :feature:navigation does not depend on PlantDetailsFragment from :feature:plant_details to navigate. MainActivity from :app:sunflower_clone handles the task as the coordinator.</li></ul><blockquote>By adopting the Coordinator Pattern, features remain independent unless explicitly connected. This prevents platform-specific dependencies from leaking between features, and makes each feature an independently reusable component.</blockquote><h4>Domain Independent Infrastructure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*C9nySPiUCcS747tFK5rj_g.png" /><figcaption>Dependencies Referencing the Core Layer in Sunflower Clone</figcaption></figure><p>Not all components in a project are tied to the business domain. Generic infrastructure that is independent of business rules can be reused in a larger scope:</p><ul><li>For example, :core:unsplash_api contains API protocols and is referenced by :data:photo to fetch photos of plants.</li><li>:core:sunflower_clone_database implements the local SQLite database and is utilized by :data:garden_planting, :data:plant, and :data:photo to persist domain entities.</li><li>:core:sunflower_clone_ui includes a shared UI kit and is used by the feature modules to standardize visual presentations.</li></ul><blockquote>The core layer allows you to extend code reuse beyond the domain boundary. It can be useful in cases such as inter-app communication, or a shared design system because two different applications can reuse the same infrastructure.</blockquote><h4>Cross-Repository Coordination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*UUH4ORKQnrxiegn6psuK4w.png" /><figcaption>Both the use case and the repository implementation can take repository instances to perform tasks</figcaption></figure><p>Just as features can depend on one another because of navigation, data modules can also become coupled for various reasons:</p><ul><li>A use case is not necessarily limited to a single repository. It may require retrieving data from multiple sources to complete a single operation.</li><li>For example, LoginUseCase may invoke the login API, and fetch the user&#39;s favorite plant list into local storage. By passing UserRepository and PlantRepository to LoginUseCase, we can perform the task, and reuse the login logic across features.</li><li>Sometimes, coupling occurs due to the design of data sources. A common case is an API response that contains data for multiple domain models.</li><li>For example, suppose an API response contains plant data along with a list of plant photos. To save this data correctly, PlantRepositoryImp can invoke PhotoRepository by passing a PhotoRepository instance to it.</li><li>However, doing this can couple the domain to the data layer by forcing PhotoRepository to expose a method for accepting response data. It is recommended that PlantRepositoryImp interact directly with the data sources to hide these implementation details.</li></ul><blockquote>Cross-repository functionality is common. A use case is generally preferred because it is more testable and reusable. We also must be careful not to let implementation details pollute business contracts.</blockquote><h4>Internal Modules within a Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*-lNkkSXzDmmWTAzbU7EDUw.png" /><figcaption>Internal Modules in Sunflower Clone</figcaption></figure><p>Sometimes, two modules within the same layer may contain duplicated logic that can be extracted into a shared module:</p><ul><li>An internal module within a layer provides a space to share logic among the modules within the same layer.</li><li>In the Sunflower Clone project, the module :app:internal:sunflower_clone_config shares metadata and DI modules across :app:sunflower_clone, :app:sunflower_clone_compose, and :app:sunflower_clone_navigation.</li><li>Internal modules should not be referenced by other layers to prevent leakage of internal logic.</li><li>If the shared code can be another normal module, it is better than introducing an internal module.</li><li>For example, the module :feature:navigation can reference :feature:plant_list to make the plant list screen one of its tab pages. :feature:plant_list remains a feature that can still be reused independently.</li></ul><blockquote>An internal module should only be introduced as a last resort to share code. Relying on LMA’s formal layer hierarchy is preferred to keep component coupling low when sharing logic.</blockquote><h4>Multiple Applications Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*n6mRq1bGhUVb-touNoE92w.png" /><figcaption>Applications in Sunflower Clone</figcaption></figure><p>Once the reusable components have been isolated, they can be combined with custom components to assemble custom applications:</p><ul><li>For example, there are multiple app modules to demonstrate the use of different navigation frameworks in Sunflower Clone. These modules are :app:sunflower_clone, :app:sunflower_clone_compose, and :app:sunflower_clone_navigation.</li><li>Each of these app modules uses a distinct navigation framework as an example of layer-specific features in the app layer. They all share the same pool of implementations.</li></ul><blockquote>We can build platform-specific app modules that uses shared components across layers, and easily swap out what needs to be customized. This flexibility also makes it possible to assemble entirely new applications from existing modules.</blockquote><h4>Need-based Modularization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*4IO3onXr93uabYbxI9-S3Q.png" /><figcaption>Creating a new feature module to reuse screen B</figcaption></figure><p>One of the major arguments against a multi-module architecture like LMA is the perceived overhead required to set up such a structure:</p><ul><li>In many cases, it is indeed unnecessary to implement such a structure before you actually need to reuse code. Why create multiple modules when a single app module works perfectly on its own?</li><li>LMA does not mandate immediate layer separation or full modularization. It only shows a roadmap of how you can divide your code to claim the various benefits that are mentioned.</li><li>A legacy project with highly coupled code can be viewed as an app module within the LMA framework because it still satisfies the architectural constraints of the app layer.</li></ul><blockquote>LMA allows implementations without full modularization. You can always write everything in the same place as long as the macro structure is not violated. The main consideration is reusability which can be traded off if you don’t need it.</blockquote><h3>Specs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*kqc77J60FVQuVE6supgz_Q.png" /><figcaption>Dependency Graph of Sunflower Clone.</figcaption></figure><p>We will refer to any module in a layer by using the layer name as a prefix. For example, a module in the core layer is called a core module.</p><h4>Core Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*GH14EdB6HEvOZP5eZ-6YKw.png" /><figcaption>Core Layer in Sunflower Clone</figcaption></figure><p><strong>Concerns:</strong></p><ul><li><strong>API Client:</strong> <br>The protocols used to communicate with external servers are considered separate from the business contracts of the project. It is usually shared across data modules.</li><li><strong>Database</strong>: <br>While a database is necessary to persist domain objects, its schema is not inherently tied to business contracts. It is usually shared across data modules.</li><li><strong>UI Kit</strong>: <br>The visual design of an application is not directly tied to business contracts, and can be reused across different UI. It is usually shared across feature modules, and app modules.</li><li><strong>Other Infrastructures</strong>: <br>Other implementations that can be decoupled from the domain model may also belong in the core layer. For example, a module that provides encryption functionality may not be directly tied to business concerns.</li></ul><p><strong>Layer-Specific Concern Criteria:</strong></p><ul><li>A core module is any component decoupled from domain logic. They are typically grouped by functional roles such as network API, UI, and database.</li></ul><p><strong>Platform Dependency:</strong></p><ul><li>A core module can be either platform-dependent or platform-independent. It depends on whether the infrastructure is platform-dependent.</li></ul><p><strong>Allowed Dependencies:</strong></p><ul><li>Core Modules</li></ul><p><strong>Disallowed Dependencies:</strong></p><ul><li>Domain Modules</li><li>Data Modules</li><li>Feature Modules</li><li>App Modules</li></ul><h4>Domain Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*pZvjYyMP19D0tz9uD4kiVw.png" /><figcaption>Domain Module in Sunflower Clone</figcaption></figure><p><strong>Concerns:</strong></p><ul><li><strong>Entities: </strong><br>Entities are data objects that represent the core concepts of the business domain. For example, PlantDO represents the concept of a plant in the Sunflower Clone project.</li><li><strong>Repository Interfaces</strong>: <br>A repository interface is responsible for abstracting data access for its entity from the rest of the project.</li><li><strong>Use Cases</strong>: <br>A use case encapsulates a single task that is part of the business logic. It is usually preferred when the task involves multiple repositories, or is complicated enough to be reused.</li><li><strong>Additional Data Types</strong>: <br>Sometimes, entities, repository interfaces, and use cases alone are not enough to represent your business domain. For instance, a business-specific exception may be required to represent a unique failure.</li></ul><p><strong>Layer-Specific Concern Criteria:</strong></p><ul><li>A domain module should encapsulate a specific business feature. For example, you might have one domain module for the vendor system and another for the payment system. In smaller projects, a single domain module is often sufficient to represent all business logic.</li></ul><p><strong>Platform Dependency:</strong></p><ul><li>A domain module should be isolated to keep your business logic separate from other concerns. Therefore, it should not be platform-dependent.</li></ul><p><strong>Allowed Dependencies:</strong></p><ul><li>Domain Modules</li></ul><p><strong>Disallowed Dependencies:</strong></p><ul><li>Core Modules</li><li>Data Modules</li><li>Feature Modules</li><li>App Modules</li></ul><h4>Data Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Pnk6bGrkoLhHn2WDi5ibQg.png" /><figcaption>Data Layer in Sunflower Clone</figcaption></figure><p><strong>Concerns:</strong></p><ul><li><strong>Entity Mappings</strong>: <br>The data layer contains the knowledge required to map DTOs (from servers or databases) to domain entities.</li><li><strong>Repository Implementations</strong>: <br>A repository implementation fulfills the contract defined by a repository interface. It handles interactions with data sources to retrieve, update, or store data.</li></ul><p><strong>Layer-Specific Concern Criteria:</strong></p><ul><li>A data module manages the data access logic for its corresponding domain entity. Typically, we create one data module for each repository defined in the domain layer.</li></ul><p><strong>Platform Dependency:</strong></p><ul><li>A data module can be either platform-dependent, or platform-independent. It is depending on whether any of its data sources are platform-dependent.</li></ul><p><strong>Allowed Dependencies:</strong></p><ul><li>Domain Modules</li><li>Core Modules</li></ul><p><strong>Disallowed Dependencies:</strong></p><ul><li>Data Modules</li><li>Feature Modules</li><li>App Modules</li></ul><h4>Feature Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*fTXbtq7wG47eeYuy2r-w1Q.png" /><figcaption>Feature Layer in Sunflower Clone</figcaption></figure><p><strong>Concerns:</strong></p><ul><li><strong>Controllers</strong>: <br>A controller is responsible for rendering the UI state, and reacting to user interactions. It is both the entry point for a screen, and the middleman between the view model and the layout.</li><li><strong>View Models</strong>: <br>A view model manages state transitions in response to user interactions from the controller. The controller uses this state to render the UI.</li><li><strong>Layouts</strong>: <br>Define how the UI is structured, such as using XML layouts or composable functions to control the visual representation.</li><li><strong>Other Platform Components</strong>: <br>An isolated functionality does not necessarily mean a screen; sometimes, it can also be a service for background task.</li></ul><p><strong>Layer-Specific Concern Criteria:</strong></p><ul><li>A feature is a user-facing functionality, and multiple features can work within the same domain. For example, both :feature:plant_list and :feature:plant_details interact with the plant domain but represent different screens.</li></ul><p><strong>Platform Dependency:</strong></p><ul><li>A feature module is platform-dependent because it represents a functionality of an application. To provide this functionality, it requires a platform-specific component to host interactions with the domain model.</li><li>It is also possible to use Compose Multiplatform (CMP) to create platform-specific features. However, it usually requires additional tweaking for each platform, so it may still be somewhat platform-dependent.</li></ul><p><strong>Allowed Dependencies:</strong></p><ul><li>Domain Modules</li><li>Core Modules</li><li>Feature Modules</li></ul><p><strong>Disallowed Dependencies:</strong></p><ul><li>Data Modules</li><li>App Modules</li></ul><h4>App Layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*dwvDuAdAwmSs4tL3drdvaQ.png" /><figcaption>App Layer in Sunflower Clone</figcaption></figure><p><strong>Concerns:</strong></p><ul><li><strong>Dependency Injection</strong>: <br>An app module typically references a set of feature modules that access data through repository interfaces. The repository implementations required by the feature modules must be injected within the app module. Sometimes, an app module may also need to inject external infrastructure, such as an API client or database, from the core layer.</li><li><strong>Navigation:</strong> <br>An app module is responsible for managing the navigation flow of features in the application to coordinate its features.</li><li><strong>Top-level Features: </strong><br>An app module includes the top-level feature to host other features and manage their interactions. This feature can contain its own controller, view model, and layout. Sometimes, an app module doesn’t need to reference feature modules and relies solely on the top-level feature to function as the application itself.</li><li><strong>Other Application Configs</strong>: <br>An application may require additional configurations at the application scope. For example, metadata required by an application should also be handled inside the app module.</li></ul><p><strong>Layer-Specific Concern Criteria:</strong></p><ul><li>An app module represents an individual application that will be installed by users. App modules are typically divided to support different versions of the same application or multiple applications that share common implementations from other layers.</li></ul><p><strong>Platform Dependency:</strong></p><ul><li>An app module is platform-dependent because it is the entry point of an application.</li></ul><p><strong>Allowed Dependencies:</strong></p><ul><li>Domain Modules</li><li>Data Modules</li><li>Feature Modules</li><li>Core Modules</li></ul><p><strong>Disallowed Dependencies:</strong></p><ul><li>App Modules</li></ul><h3>Pros, Cons, and Discussion</h3><h4>Pros of LMA</h4><ol><li><strong>Reduced Cognitive Load:<br></strong>A layer-specific feature is more focused and independent compared to domain features. This allows developers to grasp it more quickly because unrelated logic is likely kept out of the way when working on a task.</li><li><strong>Inherent Scalability:<br></strong>Adding new feature modules does not affect the stability of the project. The layered structure remains consistent regardless of the number of features.</li><li><strong>Parallel Development of Feature and Data:<br></strong>API clients are common bottlenecks in application development. Developers often have to wait for backend side to complete before they can resume. LMA separates the data implementation from feature modules, and allows features to be developed independently.</li><li><strong>Reduced Incremental Build Time:<br></strong>The ripple effect of a single edit to the code is greatly reduced thanks to the smaller building blocks of LMA. Handling dependency injection in a single module for each application also reduces build time because class path aggregation in a multi-module setup can be time-consuming.</li></ol><h4>Cons of LMA</h4><ol><li><strong>Steep Learning Curve:<br></strong>LMA builds upon the foundation of Clean Architecture. The combination of various software patterns makes LMA a complex concept. However, the rules of LMA are solid and easy to follow, even for someone who doesn’t understand the theories behind it.</li><li><strong>Discipline to Maintain Dependency Rules:</strong><br>The flexibility of LMA can be a double-edged sword. There is nothing to enforce the separation of dependencies, and is easy for an unfamiliar developer to violate the project structure by establishing a prohibited reference in the code.</li><li><strong>Overhead for Small Projects:<br></strong>Sometimes an application is too small to justify the need for an architecture. An application with a single feature doesn’t need a feature layer. However, it is rare for any application to remain at the same scale anyway. If an application fails to establish an architecture that is inherently scalable, it will require an overhaul to expand functionality. As for LMA, you can always divide as you go, as long as the macro structure remains consistent.</li><li><strong>Dependency Exceptions:</strong><br>Depending on how DI is implemented in the project, an unsatisfied dependency may remain hidden until runtime. This can be problematic if it is not covered by tests. However, such issues should be detectable during application startup if lazy loading is not used, and lazy loading is generally unnecessary for repository injection.</li></ol><h3>Conclusion</h3><p>For a long time, people have searched for ways to solve various software development problems. Scrum was introduced to apply Agile principles to shorten delivery cycles, project management tools were implemented to handle team coordination, and cross-platform frameworks were released to reuse implementation. All these solutions fail to fully solve the problems because architecture as the fundamental factor is often overlooked.</p><p>How do you make swift changes if every edit requires reviewing a vast amount of code? How does a team work together if there are no boundaries in the system to divide tasks? How do you share implementations across platforms when the platform logic and code are tightly coupled? Without a good architecture, all external methods inevitably result in flaws.</p><p>LMA provides a solid macro-structure that allows micro-changes within well-defined boundaries. This is exactly the key to rapid edits, team cooperation, and code reuse.</p><ul><li><a href="https://github.com/Deathhit/SunflowerClone">GitHub - Deathhit/SunflowerClone: Android application architecture example composed of MVVM, UDF and modularization</a></li><li><a href="https://github.com/Deathhit/TaipeiTour/tree/master">GitHub - Deathhit/TaipeiTour: Android application architecture example composed of MVVM, UDF and modularization</a></li></ul><p><a href="https://codeberg.org/zerg_1111/LMA_Samples">https://codeberg.org/zerg_1111/LMA_Samples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dee729f6e1f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>