Skip to content

Instantly share code, notes, and snippets.

View vitalikas's full-sized avatar

Vitalikas vitalikas

  • Lithuania
View GitHub Profile
@vitalikas
vitalikas / coroutine_cancellation.kt
Last active December 11, 2025 12:49
Coroutine cancellation examples
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
inline fun <R> runCatchingWithCancellation(block: () -> R): Result<R> {
return try {
Result.success(block())
@vitalikas
vitalikas / inline_fun.kt
Created December 11, 2025 07:12
Inline, noinline and crossinline example in Kotlin
/**
* Demonstrates inline, noinline, and crossinline in one function.
*
* - onSuccess: regular inline lambda - you can use 'return' to exit the calling function
* - noinline onError: can be passed to other functions that expect function types
* - crossinline onComplete: inline but called later (e.g., in a callback), no 'return' allowed
*/
inline fun String.validateEmail(
onSuccess: () -> Unit,
noinline onError: (String) -> Unit,
@vitalikas
vitalikas / SupervisorJob_examples.kt
Last active December 5, 2025 08:54
SupervisorJob vs Regular Job - Complete Demonstration (FAST VERSION)
/**
* SupervisorJob vs Regular Job - Complete Demonstration (FAST VERSION)
*
* This version uses shorter delays (100ms instead of 3-5 seconds) for online playgrounds
*
* Run in Kotlin Playground: https://play.kotlinlang.org/
*/
import kotlinx.coroutines.*
@vitalikas
vitalikas / flow.kt
Created December 4, 2025 13:24
Flow examples
fun main() {
runBlocking {
println("=== Example 1: Cold Flow (default behavior) ===")
// Cold flow: executes independently for each collector
val coldFlow = flow {
println("Cold Flow started")
emit("A")
delay(100)
emit("B")
}
@vitalikas
vitalikas / solid.kt
Created November 20, 2025 08:40
SOLID example
interface SortingStrategy<T : Comparable<T>> {
fun sort(data: List<T>): List<T>
}
enum class StrategyType {
BUBBLE, MERGE, QUICK
}
class BubbleSortStrategy<T : Comparable<T>> : SortingStrategy<T> {
override fun sort(data: List<T>): List<T> {
@vitalikas
vitalikas / mvi_viewmodel.kt
Last active July 4, 2025 12:34
generic MVI viewmodel
abstract class MVIViewModel<STATE, EVENT, EFFECT>(
protected val savedStateHandle: SavedStateHandle? = null,
protected val effectDelegate: AutoConsumableEffect<EFFECT>,
) : ViewModel(), AutoConsumableEffect<EFFECT> by effectDelegate {
abstract val initialState: STATE
private val _uiState by lazy { MutableStateFlow(initialState) }
val uiState = _uiState.asStateFlow()