Skip to content

Instantly share code, notes, and snippets.

@ajinkya5130
Last active February 28, 2026 06:46
Show Gist options
  • Select an option

  • Save ajinkya5130/bf36c790941676c98557b750421a466a to your computer and use it in GitHub Desktop.

Select an option

Save ajinkya5130/bf36c790941676c98557b750421a466a to your computer and use it in GitHub Desktop.
Compose UI Screen with ViewModel
/**
Created by ${USER} on ${DATE}
*/
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end
sealed interface ${NAME}Action {
}
/**
Created by ${USER} on ${DATE}
*/
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "") package ${PACKAGE_NAME} #end
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun ${NAME}Root(
viewModel: ${NAME}ViewModel = viewModel()
) {
val state by viewModel.state.collectAsStateWithLifecycle()
${NAME}Screen(
state = state,
onAction = viewModel::onAction
)
}
@Composable
fun ${NAME}Screen(
state: ${NAME}State,
onAction: (${NAME}Action) -> Unit,
) {
}
@Preview
@Composable
private fun Preview() {
${PROJECT_NAME}Theme {
${NAME}Screen(
state = ${NAME}State(),
onAction = {}
)
}
}
/**
Created by ${USER} on ${DATE}
*/
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end
data class ${NAME}State(
val paramOne: String = "default",
val paramTwo: List<String> = emptyList(),
)
/**
Created by ${USER} on ${DATE}
*/
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
class ${NAME}ViewModel : ViewModel() {
private var hasLoadedInitialData = false
private val _state = MutableStateFlow(${NAME}State())
val state = _state
.onStart {
if(!hasLoadedInitialData) {
/** Load initial data here **/
hasLoadedInitialData = true
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = ${NAME}State()
)
fun onAction(action: ${NAME}Action) {
when(action) {
else -> TODO("Handle actions")
}
}
}
@ajinkya5130
Copy link
Author

  1. go to any package.
  2. right click on it.
  3. click on new
  4. edit file template
  5. click on Plus (+) icon.
  6. add one by one code in the empty area
  7. mention name as a mention as a file name and extension as .kt
  8. refer the ScreenShot attached.
    a. ${ScreenName}Root.kt
    i. ${NAME}ViewModel.kt
    ii. ${NAME}State.kt
    iii. ${NAME}Action.kt
Screenshot 2026-02-28 at 11 18 51 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment