Skip to content

Instantly share code, notes, and snippets.

View nextersolutions's full-sized avatar

Andrii Dubovyk nextersolutions

View GitHub Profile
fun processPayment(
order: Order,
analytics: AnalyticsContext // the uninvited guest at every layer
) {
analytics.track("payment_started", order.id)
}
data class AnalyticsContext(
val sessionId: String,
val experimentVariant: String,
) {
fun track(event: String, payload: Any) { /* ... */ }
}
context(analytics: AnalyticsContext)
fun processPayment(order: Order) {
analytics.track("payment_started", order.id)
interface Logger {
fun log(message: String)
}
context(logger: Logger)
fun fetchUserData(userId: String): User {
logger.log("Fetching user: $userId")
// actual fetch logic
return User(userId)
}
data class MyState(val counter: Int = 0)
class MyViewModel : ViewModel() {
private val _state = MutableStateFlow(MyState())
val state: StateFlow<MyState> = with(viewModelScope) {
_state
.onStart { /* warm-up logic */ }
.stateInWhileSubscribed(initialValue = MyState())
context(scope: CoroutineScope)
fun <T> Flow<T>.stateInWhileSubscribed(initialValue: T): StateFlow<T> =
stateIn(
scope,
SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000L),
initialValue
)
fun <T> ViewModel.stateInWhileSubscribed(
initialValue: T
): StateFlow<T> = stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000L),
initialValue
)