Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple way to jump into a separate context
suspend fun <T, R> T.letOn(
context: CoroutineContext,
block: suspend CoroutineScope.(T) -> R
): R = withContext(context) { block(this@letOn) }
suspend fun <T> T.alsoOn(
context: CoroutineContext,
block: suspend CoroutineScope.(T) -> Unit
): T = also { withContext(context) { block(this@alsoOn) } }
suspend fun <T> T.applyOn(
context: CoroutineContext,
block: suspend T.(CoroutineScope) -> Unit
): T = apply { withContext(context) { this@applyOn.block(this) } }
suspend fun <T, R> T.runOn(
context: CoroutineContext,
block: suspend T.(CoroutineScope) -> R
): R = withContext(context) { this@runOn.block(this) }

Before

launch {
  val data = fetchFromNetwork().map { it.toModel() }

  withContext(Main) {
    updateUi(data)
  }
}

After

launch {
  fetchData()
    .map { it.toModel() }
    .alsoOn(Main) { data ->
      updateUi(data) 
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.