https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

gumil

07/18/2020, 11:04 AM
Hello people, is it okay to make use of
yield
in production code? I rarely see it being used and only seen it used in tests. I wanted to know people's opinion if they ever used this function.
d

dekans

07/18/2020, 12:31 PM
I already used it to force dispatch in order to avoir a concurrency exception
It can be useful in a producer use case also.
g

gumil

07/18/2020, 12:36 PM
Interesting, I have to add yield in my case because my unit tests are single threaded and using
FlowState
it only emits the last value without the yield.
z

Zach Klippenstein (he/him) [MOD]

07/19/2020, 10:12 PM
It’s definitely production ready. Although if just adding a
yield()
call fixes something and you’re not sure why, it’s dangerous to rely on that without figuring out what’s really going on. Adding it to production code in to make your tests work is definitely something I would consider a smell. In your example, it sounds like you’re trying to observe intermediate values in a sequence of state transitions, which is an odd thing to test since your production code is probably just as likely to not observe intermediate values.
g

gumil

07/19/2020, 10:38 PM
In production code this intermediate values actually emits because the coroutines are ran on different threads. I have a network call that runs on the io thread and a flowstate that runs in the main thread. And when they are running on the same thread, flowstate is not able to collect intermediate values. I think it works for now having this yield because in native code the coroutines run only on a single thread
11 Views