Channels发送和提供之间的用法差异

Channels发送和提供之间的用法差异

本文介绍了Kotlin Channels发送和提供之间的用法差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通道具有两个功能,可让我们向其中发送事件.Sendoffer.

Channels have two functions that allow us to send events into it.Send and offer.

我想更好地了解两者之间的区别.

I would like to understand better the difference between both.

我有一些想核对的陈述.

I have some statements I wanna check are true.

  • Send是挂起函数.是什么让我的代码(不是线程)等待它完成.因此,它在send内部的事件完成/取消后继续运行.还是只有在我可以将事件排队/接收事件之前才会暂停?
  • 这意味着,如果我从一个通道到另一个通道使用send,第一个通道将被阻塞,直到第二个通道可以接收/排队?
  • 如果我有一个 Rendezvous 频道,并且它已经在运行某些内容(例如,在暂停状态下,正在等待API),并且我offer一个新的偶数.这会使offer引发异常吗?导致频道无法接收?
  • Send is a suspend function. What will make my code(not the thread) wait for it to finish. So it keep running after the event inside send was complete/cancelled. OR it will be suspend only until I can queue the event/receive it?
  • This means that, if I use send from one channel to another, the first channel will be block until the second can receive/queue?
  • If I have a Rendezvous Channel and it is already running something (on suspend for example, waiting API) and I offer a new even. This will make offer throws exception? Cause the channel is not receiving?

如果您知道任何其他主要区别,我将很高兴知道.

If you know any other main difference I would be glad to know.

预先感谢

推荐答案

send 在发送到的频道已满时,暂停从其调用的协程.

send suspends the coroutine it is invoked from while the channel being sent to is full.

send不会从一个通道向另一个通道发送.调用send时,您正在向该通道发送 元素.然后,该通道期望另一个代码块从其他协程调用receive.

send does not send from one channel to another one. When you invoke send you are sending an element to the channel. The channel then expects another block of code to invoke receive from a different coroutine.

RendezvousChannel中,容量为0.这意味着send总是挂起,等待来自另一个协程的receive调用.如果您已在RendezvousChannel上调用send,然后使用offer,则 offer 不会引发异常(仅在关闭通道的情况下会发生),但是如果没有平衡,它将返回false初始send之后,已在RendezvousChannel上调用了receive.这是因为offer会尝试在不违反其容量限制的情况下立即将元素添加到通道中.

In a RendezvousChannel the capacity is 0. This means that send always suspends waiting for a receive invocation from another coroutine. If you have invoked send on a RendezvousChannel and then use offer, offer will not throw an exception (it only does if the channel is closed), but rather it will return false if no balancing receive has been invoked on the RendezvousChannel after your initial send. This is because offer tries to immediately add the element to the channel if it doesn't violate its capacity restrictions.

这篇关于Kotlin Channels发送和提供之间的用法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:50