Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active January 11, 2024 16:42
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/f83f98e427acb55435a02880f1efbff2 to your computer and use it in GitHub Desktop.
Save pablisco/f83f98e427acb55435a02880f1efbff2 to your computer and use it in GitHub Desktop.
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