Skip to content
Snippets·Free

Kotlin and Android snippets

20 Kotlin snippets for Android apps: sealed UI state, a Hilt ViewModel with StateFlow, coroutines, Room entities and DAOs, and Compose state and lists. Type a prefix such as uistate or hiltvm in a .kt file.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 20

Sealed UI stateuistate

Loading, success and error states for a screen

sealed interface ${1:Ui}State {
    data object Loading : ${1:Ui}State
    data class Success(val ${2:data}: ${3:String}) : ${1:Ui}State
    data class Error(val message: String) : ${1:Ui}State
}

Hilt ViewModel with StateFlowhiltvm

ViewModel with an injected repository and a read-only state

@HiltViewModel
class ${1:Feature}ViewModel @Inject constructor(
    private val ${2:repository}: ${3:Repository},
) : ViewModel() {

    private val _state = MutableStateFlow(${1:Feature}UiState())
    val state: StateFlow<${1:Feature}UiState> = _state.asStateFlow()

    fun ${4:load}() {
        viewModelScope.launch {
            $0
        }
    }
}

Update StateFlow statestupd

Change a field of the state with update and copy

_state.update { it.copy(${1:isLoading = true}) }

Collect state in Composecollectst

Read a StateFlow in a composable, aware of the lifecycle

val ${1:state} by ${2:viewModel}.${3:state}.collectAsStateWithLifecycle()

Switch to the IO dispatcherwithio

Suspend function that runs blocking work off the main thread

suspend fun ${1:loadData}(): ${2:String} = withContext(Dispatchers.IO) {
    ${3:TODO()}
}

Changes in 1.0.0

First version.

Related