Skip to content

Add memory leak examples for Android documentation#920

Open
sudeshim3 wants to merge 2 commits into
mainfrom
feature/memory-leak-snippets
Open

Add memory leak examples for Android documentation#920
sudeshim3 wants to merge 2 commits into
mainfrom
feature/memory-leak-snippets

Conversation

@sudeshim3
Copy link
Copy Markdown
Collaborator

  • Add Pattern 1: UI Objects Retained Beyond Lifecycle examples
  • Add Pattern 2: Background Work Outlives the UI examples
  • Add Pattern 3: Unreleased External Registrations examples
  • Include Compose and Fragment-specific memory management best practices
  • Ensure snippets are idiomatic and comply with Spotless formatting

These examples illustrate common architectural pitfalls and their corresponding lifecycle-aware resolutions using Coroutines, Flows, and DisposableEffect.

@sudeshim3 sudeshim3 requested review from a team, kkuan2011 and yrezgui as code owners May 14, 2026 17:20
@sudeshim3 sudeshim3 requested a review from dturner May 14, 2026 17:20
@snippet-bot
Copy link
Copy Markdown

snippet-bot Bot commented May 14, 2026

Here is the summary of changes.

You are about to add 13 region tags.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@sudeshim3 sudeshim3 requested a review from AliceYuan May 14, 2026 17:21
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive set of code snippets demonstrating common memory leak patterns in Android and Compose, such as retained UI callbacks, improper lifecycle management for Flow collection, and uncleared view bindings. Feedback includes a recommendation to use repeatOnLifecycle for Flow collection in the Activity example to ensure efficiency and consistency with best practices. Additionally, it was suggested to re-categorize the fragment view binding example under Pattern 1 for improved documentation accuracy.

Comment on lines +206 to +210
lifecycleScope.launch {
UserRepositoryDelayedRecommended.getUserData().collect { data ->
title = data
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For collecting flows in the UI, it is recommended to use repeatOnLifecycle to ensure that the collection only occurs when the Activity is in a visible state (e.g., STARTED). This is more efficient and consistent with the best practices shown in the Fragment example earlier in this file.

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                UserRepositoryDelayedRecommended.getUserData().collect { data ->
                    title = data
                }
            }
        }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like gemini detected the code smell we're trying to show as an example

}
// [END android_memory_leak_delayed_work_recommended]

// Pattern 3: Example 2 - Fragment view binding is not cleared
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This example (Fragment view binding not cleared) belongs to Pattern 1: UI Objects Retained Beyond Lifecycle rather than Pattern 3 (External Registrations). Pattern 3 typically involves listeners or observers registered with system services or external components. Correcting this label will improve the documentation's accuracy.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I agree with this assessment actually should we remove? It seems fairly similar as Pattern 1, option2.

I don't think a 2nd example is needed

* Add Pattern 1: UI Objects Retained Beyond Lifecycle examples
* Add Pattern 2: Background Work Outlives the UI examples
* Add Pattern 3: Unreleased External Registrations examples
* Include Compose and Fragment-specific memory management best practices
* Ensure snippets are idiomatic and comply with Spotless formatting

These examples illustrate common architectural pitfalls and their
corresponding lifecycle-aware resolutions using Coroutines,
Flows, and DisposableEffect.
@sudeshim3 sudeshim3 force-pushed the feature/memory-leak-snippets branch from 671a754 to 8e3a6cc Compare May 14, 2026 17:25
}
}

/* In the Fragment/UI layer:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of showing commented out code you should show the actual compileable code, also I think you could show this occuring within a view model instead of calling from activity to avoid other code smells.

binding.name.text = user.name
}
*/
// [END android_memory_leak_repository_callback_recommended]
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommend creating 2 code snippets here if the intention is to show repository.fetchUser() getting called. What I mean is it could look something like:

// [START android_memory_leak_repository_callback_recommended_pt1]
class UserRepositoryRecommended {
    suspend fun fetchUser(): User {
        return api.getUser()
    }
}
// [END android_memory_leak_repository_callback_recommended_pt1]

class UserViewModel(private val repository: UserRepositoryRecommended) : ViewModel() {

    private val _userState = MutableStateFlow<User?>(null)
    val userState: StateFlow<User?> = _userState.asStateFlow()

// [START android_memory_leak_repository_callback_recommended_pt2]
    fun loadUser() {
        // viewModelScope automatically cancels if the user leaves the screen
        viewModelScope.launch {
                val user = repository.fetchUser()
                _userState.value = user
        }
    }
// [END android_memory_leak_repository_callback_recommended_pt2]
}

// Accepts a callback that might capture a destroyed UI Context
fun fetchUserDataWithDelay(onComplete: (String) -> Unit) {
repositoryScope.launch {
delay(5_000)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggest adding some explanation that the delay is to emulate network or processing.

object UserRepositoryDelayedRecommended {
// A clean, stateless flow with no callback parameters
fun getUserData(): Flow<String> = flow {
delay(5_000)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggest adding some explanation that the delay is to emulate network or processing.

}
}

/* In the Fragment/UI layer:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same recommendation to actually create the Activity (or ViewModel) that calls the repository.

Comment on lines +206 to +210
lifecycleScope.launch {
UserRepositoryDelayedRecommended.getUserData().collect { data ->
title = data
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like gemini detected the code smell we're trying to show as an example

}
// [END android_memory_leak_delayed_work_recommended]

// Pattern 3: Example 2 - Fragment view binding is not cleared
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I agree with this assessment actually should we remove? It seems fairly similar as Pattern 1, option2.

I don't think a 2nd example is needed

* Refactor Repository examples to use actual ViewModel implementations
  instead of commented-out pseudo-code.
* Split the recommended Repository callback snippet into pt1 and pt2.
* Add explanatory comments to delay() calls clarifying their purpose
  to emulate network/processing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants