Skip to content
Development
Skill

/kotlin-patterns

Coroutine patterns, Flow operators, Jetpack Compose state management, Ktor routing, and Kotlin Multiplatform shared code.

From plugin
vibecosystem
532200 skills138 agents7 hooks
Install
$ npx -y skills add vibeeval/vibecosystem --skill kotlin-patterns --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/kotlin-patterns

Context preview

The summary Claude sees to decide when to auto-load this skill.

Coroutine patterns, Flow operators, Jetpack Compose state management, Ktor routing, and Kotlin Multiplatform shared code.

SKILL.md

kotlin-patterns.SKILL.md
name: kotlin-patterns
description: Coroutine patterns, Flow operators, Jetpack Compose state management, Ktor routing, and Kotlin Multiplatform shared code.

Kotlin Patterns

Modern Kotlin patterns for Android, server-side, and multiplatform development.

Coroutine Patterns

import kotlinx.coroutines.*

// Structured concurrency: child failures cancel siblings
suspend fun loadDashboard(): Dashboard = coroutineScope {
    val profile = async { api.fetchProfile() }
    val orders = async { api.fetchRecentOrders() }
    val stats = async { api.fetchStats() }

    // All run concurrently; if one fails, others are cancelled
    Dashboard(
        profile = profile.await(),
        orders = orders.await(),
        stats = stats.await()
    )
}

// SupervisorScope: child failures don't cancel siblings
suspend fun loadOptionalData(): HomeScreen = supervisorScope {
    val required = async { api.fetchRequiredData() }
    val optional = async {
        try { api.fetchRecommendations() }
        catch (e: Exception) { emptyList() }  // Graceful fallback
    }

    HomeScreen(
        data = required.await(),
        recommendations = optional.await()
    )
}

// Retry with exponential backoff
suspend fun <T> retryWithBackoff(
    maxRetries: Int = 3,
    initialDelayMs: Long = 1000,
    factor: Double = 2.0,
    block: suspend () -> T
): T {
    var currentDelay = initialDelayMs
    repeat(maxRetries - 1) { attempt ->
        try {
            return block()
        } catch (e: Exception) {
            if (e is CancellationException) throw e  // Never swallow cancellation
            delay(currentDelay)
            currentDelay = (currentDelay * factor).toLong()
        }
    }
    return block()  // Last attempt, let exception propagate
}

Flow Operators

import kotlinx.coroutines.flow.*

// Repository pattern with Flow
class OrderRepository(private val api: OrderApi, private val db: OrderDao) {

    // Offline-first: emit cached, then fetch fresh
    fun getOrders(): Flow<List<Order>> = flow {
        // Emit cached data first
        emit(db.getAllOrders())

        // Fetch fresh data
        val fresh = api.fetchOrders()
        db.insertAll(fresh)
        emit(fresh)
    }.catch { e ->
        // On network error, emit cached data
        emit(db.getAllOrders())
    }

    // Debounce search input
    fun search(queryFlow: Flow<String>): Flow<List<Order>> =
        queryFlow
            .debounce(300)
            .distinctUntilChanged()
            .filter { it.length >= 2 }
            .flatMapLatest { query ->
                flow { emit(api.search(query)) }
                    .catch { emit(emptyList()) }
            }

    // Combine multiple flows
    fun getDashboard(): Flow<DashboardState> =
        combine(
            getOrders(),
            getStats(),
            getNotifications()
        ) { orders, stats, notifications ->
            DashboardState(orders, stats, notifications)
        }
}

// StateFlow for UI state (hot flow, always has value)
class OrderViewModel(private val repo: OrderRepository) : ViewModel() {

    private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            repo.getOrders()
                .map { orders -> UiState.Success(orders) as UiState }
                .catch { emit(UiState.Error(it.message ?: "Unknown error")) }
                .collect { _uiState.value = it }
        }
    }

    sealed interface UiState {
        data object Loading : UiState
        data class Success(val orders: List<Order>) : UiState
        data class Error(val message: String) : UiState
    }
}

Jetpack Compose State

@Composable
fun OrderListScreen(viewModel: OrderViewModel = viewModel()) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    when (val state = uiState) {
        is UiState.Loading -> LoadingIndicator()
        is UiState.Error -> ErrorMessage(state.message) { viewModel.retry() }
        is UiState.Success -> OrderList(
            orders = state.orders,
            onOrderClick = { viewModel.selectOrder(it) },
            onDelete = { viewModel.deleteOrder(it) }
        )
    }
}

// Stateless composable with hoisted state
@Composable
fun OrderList(
    orders: List<Order>,
    onOrderClick: (Order) -> Unit,
    onDelete: (Order) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(modifier = modifier) {
        items(orders, key = { it.id }) { order ->
            OrderItem(
                order = order,
                onClick = { onOrderClick(order) },
                onDelete = { onDelete(order) },
                modifier = Modifier.animateItem()
            )
        }
    }
}

// Remember expensive computation
@Composable
fun FilteredOrders(orders: List<Order>, filter: String) {
    val filtered = remember(orders, filter) {
        orders.filter { it.status.name.contains(filter, ignoreCase = true) }
    }
    OrderList(orders = filtered, onOrderClick = {}, onDelete = {})
}

Ktor Server Routing

import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.server.request.*
import io.ktor.http.*

fun Application.configureRouting() {
    routing {
        route("/api/v1") {
            // Middleware: auth check for all routes under /api/v1
            install(AuthPlugin)

            route("/orders") {
                get {
                    val page = call.parameters["page"]?.toIntOrNull() ?: 1
                    val limit = call.parameters["limit"]?.toIntOrNull()?.coerceIn(1, 100) ?: 20
                    val orders = orderService.findAll(page, limit)
                    call.respond(ApiResponse.success(orders))
                }

                get("/{id}") {
                    val id = call.parameters["id"]
                        ?: return@get call.respond(HttpStatusCo
Read more
Ships withvibecosystem

Your AI software team. Built on Claude Code. vibecosystem turns Claude Code into a full AI software team — 138 specialized agents that plan, build, review, test, and learn from every mistake. No configuration needed — just install and code.

Get the whole plugin

Other skills on vibecosystem.