Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
How do you know when you need to yield()?

Take Kotlin channels for example

for(msg in channel){
    // to stuff
    yield() // maybe?
}

How do you know if yield is required? I assume that Channels are built in a way that yielding happens automatically behind the scenes in the iterator but I'm not sure. In general, how do you know you need manual yields when using the rest of Kotlin's coroutine library that might do it for you automatically?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In most cases you should not at all need to use yield() or be concerned with it. Coroutines can switch automatically whenever we get to a suspension point, which usually happens pretty often.

yield() is needed only if our code does not suspend for prolonged time. That usually means we are performing intensive CPU calculations. In your example receiving from the channel is suspending operation, so you don't need yield() here.

over 4 years ago · Santiago Trujillo Relatório

0

You only need to call yield if you want to artificially add a suspension point when you have none in a piece of code. Suspension points are calls to suspend functions.

If you don't know which functions are suspend from the top of your head, you can quickly identify those in IntelliJ IDEA for instance because every suspend function call is marked with an icon:

enter image description here

So in your case you would see it on the iteration over the channel:

channel iteration with suspension icon

You only really need to manually add a yield if you have loops or extended pieces of code that exclusively use regular functions, or more generally if you want to ensure other coroutines have a chance to run at a particular point in time (for instance in tests). This shouldn't happen often.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda