Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created August 14, 2019 12:50
Show Gist options
  • Save yaraki/4c77f59c5b10f486243c89c4aa69e5d1 to your computer and use it in GitHub Desktop.
Save yaraki/4c77f59c5b10f486243c89c4aa69e5d1 to your computer and use it in GitHub Desktop.
Channel vs. Flow
package com.example.playground
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.channels.toList
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
class CoroutineTest {
@Test
fun channel() = runBlocking {
val called = AtomicBoolean(false)
assertThat(called.get()).isFalse()
val c: ReceiveChannel<Int> = produce {
called.set(true)
channel.send(1)
}
assertThat(called.get()).isFalse()
yield()
assertThat(called.get()).isTrue()
val result = c.toList().single()
assertThat(called.get()).isTrue()
assertThat(result).isEqualTo(1)
}
@Test
fun flow() = runBlocking {
val called = AtomicBoolean(false)
assertThat(called.get()).isFalse()
val f = flow {
called.set(true)
emit(1)
}
assertThat(called.get()).isFalse()
yield()
assertThat(called.get()).isFalse()
val result = f.single()
assertThat(called.get()).isTrue()
assertThat(result).isEqualTo(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment