Skip to content

Repository files navigation

CoroutineKit

License: MIT Kotlin Maven Central

Production-grade Kotlin coroutine utilities for Android & JVM. Write safer, cleaner, and more testable asynchronous code — without reinventing the wheel.


✨ Features

Module What it gives you
FlowExt throttleFirst, retryWithDelay, onEachCatching and more Flow operators
SuspendExt suspendRunCatching (CancellationException-safe), withTimeoutOrDefault, launchCatching
ManagedScope Lifecycle-aware CoroutineScope with SupervisorJob and Closeable
RetryPolicy Fixed, Exponential Backoff, and Immediate retry strategies
JavaInterop CompletableFuture bridge + universal Callback → Flow adapter
DispatcherUtils Centralized, test-mockable dispatcher provider

📦 Installation

Add the dependency to your module's build.gradle.kts:

dependencies {
    implementation("com.yangcyzhang:coroutinekit:0.1.0")
}

Make sure mavenCentral() is in your repository list.


🚀 Quick Start

1. Safe suspend calls — suspendRunCatching

// Never accidentally swallows CancellationException
val result: Result<User> = suspendRunCatching {
    userRepository.fetchUser(id)
}
result.onSuccess { user -> render(user) }
      .onFailure { e -> showError(e) }

2. Timeout with fallback — withTimeoutOrDefault

val data = withTimeoutOrDefault(timeMillis = 3_000, defaultValue = emptyList()) {
    networkService.fetchFeed()
}

3. Flow — throttleFirst (great for UI click events)

buttonClickFlow
    .throttleFirst(windowDuration = 500)
    .onEach { handleClick() }
    .launchIn(viewModelScope)

4. Flow — retryWithDelay (exponential backoff built-in)

apiFlow
    .retryWithDelay(times = 3, initialDelay = 200, factor = 2.0)
    .collect { result -> process(result) }

5. ManagedScope — lifecycle-safe background scope

class MyRepository : Closeable {
    private val scope = ManagedScope(Dispatchers.IO)

    fun startSync() = scope.launch {
        while (isActive) {
            sync()
            delay(30_000)
        }
    }

    override fun close() = scope.close() // cancels everything safely
}

6. Retry Policies

// Exponential backoff: 100ms → 200ms → 400ms → ...
val result = withRetry(
    policy = RetryPolicy.ExponentialBackoff(times = 4, initialDelayMs = 100)
) { attempt ->
    println("Attempt $attempt")
    apiCall()
}

7. Java Interop — CompletableFuture bridge

// Expose a suspend function to Java callers
val future: CompletableFuture<User> = suspendToFuture {
    userRepository.fetchUser(id)
}

8. Java Interop — Callback → Flow

val sensorFlow: Flow<SensorData> = callbackFlow(
    register = { onResult, onError ->
        sensorManager.register(object : SensorListener {
            override fun onData(d: SensorData) = onResult(d)
            override fun onError(e: Throwable) = onError(e)
        })
    },
    unregister = { sensorManager.unregister() }
)

🧪 Running Tests

./gradlew :coroutinekit:test

🤝 Contributing

Contributions are welcome! Please read CONTRIBUTING.md before submitting a pull request.


📄 License

MIT License — Copyright (c) 2026 yangcyzhang

See LICENSE for full text.

About

Production-grade Kotlin coroutine utilities for Android and JVM, designed to write safer, cleaner, and more testable asynchronous code.

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages