Using Sink to send data back

Future and Stream objects supply data from a source, but if you want to send a piece of data to the source, you have to use Sink objects. Sink is a trait that is similar to Stream, but works in the opposite direction. It contains two associated types—SinkItem and SinkError. The first determines the type of item that can be sent using a specific sink. The second represents an error if the sending process goes wrong. To interact with a Sink, you should use the methods of the SinkExt trait, which contains send methods to send an item to a recipient. The send method returns a Send struct that implements the Future trait, which means you can't send an item immediately. The call of the send methods returns a future that has to be executed with a reactor. If you are not concerned about the result of the sending process, you can use the spawn method to send the future in a separate task.

The Sink object comes with Stream and you have to call the split method of StreamExt to get an instance of Sink attached to a stream. This call returns a tuple with both SplitSink and  SplitStream objects. These are necessary to let you read an input and write an output concurrently. Later, both of these can be reunited using the reunite method of any of these objects. If you are writing a complex interaction, you have to use a Sink trait many times. It's hard to do this using split every time, but there are two alternative approaches that you can use. The first is to implement all interactions in a separate implementation of the Stream trait and work with a Stream and a Sink using the poll method. The second approach is to split a sink and join it with a Receiver object of a channel. You can then use a Sender of this channel to send an item without splitting the stream every time. We will implement an example of this kind of interaction in the next section, in which we will discuss channels.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.81