android-viewmodel

Android ViewModel & State Management

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "android-viewmodel" with this command: npx skills add new-silvermoon/awesome-android-agent-skills/new-silvermoon-awesome-android-agent-skills-android-viewmodel

Android ViewModel & State Management

Instructions

Use ViewModel to hold state and business logic. It must outlive configuration changes.

  1. UI State (StateFlow)
  • What: Represents the persistent state of the UI (e.g., Loading , Success(data) , Error ).

  • Type: StateFlow<UiState> .

  • Initialization: Must have an initial value.

  • Exposure: Expose as a read-only StateFlow backing a private MutableStateFlow . private val _uiState = MutableStateFlow<UiState>(UiState.Loading) val uiState: StateFlow<UiState> = _uiState.asStateFlow()

  • Updates: Update state using .update { oldState -> ... } for thread safety.

  1. One-Off Events (SharedFlow)
  • What: Transient events like "Show Toast", "Navigate to Screen", "Show Snackbar".

  • Type: SharedFlow<UiEvent> .

  • Configuration: Must use replay = 0 to prevent events from re-triggering on screen rotation. private val _uiEvent = MutableSharedFlow<UiEvent>(replay = 0) val uiEvent: SharedFlow<UiEvent> = _uiEvent.asSharedFlow()

  • Sending: Use .emit(event) (suspend) or .tryEmit(event) .

  1. Collecting in UI
  • Compose: Use collectAsStateWithLifecycle() for StateFlow . val state by viewModel.uiState.collectAsStateWithLifecycle()

For SharedFlow , use LaunchedEffect with LocalLifecycleOwner .

  • Views (XML): Use repeatOnLifecycle(Lifecycle.State.STARTED) within a coroutine.
  1. Scope
  • Use viewModelScope for all coroutines started by the ViewModel.

  • Ideally, specific operations should be delegated to UseCases or Repositories.

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Automation

gradle-build-performance

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

compose-ui

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

kotlin-concurrency-expert

No summary provided by upstream source.

Repository SourceNeeds Review