Skip to content

Instantly share code, notes, and snippets.

@fvasco
fvasco / switchMap.kt
Created August 1, 2018 09:15
ReceiveChannel<E>.switchMap
fun <E : Any, R> ReceiveChannel<E>.switchMap(context: CoroutineContext = DefaultDispatcher,
transform: suspend (E) -> ReceiveChannel<R>): ReceiveChannel<R> =
produce(context) {
var originChannel: ReceiveChannel<E>? = this@switchMap
var itemChannel = this@switchMap.receiveOrNull()?.let { transform(it) } ?: return@produce
var itemToSend: R? = null
whileSelect {
originChannel?.onReceiveOrNull?.invoke { newItem ->
if (newItem == null) originChannel = null // origin closed
private val lsClient = LightstreamerClient(
resources.getString(R.string.host),
"DEMO")
.apply {
connect()
}