Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elixir
stream

How to store a result in a composable stream in Elixir

Abdul Mateen

Streams in Elixir

Any enumerable that produces elements one by one during an enumeration is called a stream. Streams are composable and lazy enumerables.

Note: Streams do not operate unless it is needed.

Why so lazy?

Streams are lazy because they apply transformations to the enumerable elements and store computations. So, when we run the stream, elements go one by one through those computations.

Streams do not save all their contents in the memory. Instead, they produce data items one by one and pass them along when needed to be altered or transformed. They utilize a buffer for storing data until some other process requires it.

Storing results

To store the results, treat it as a collection and pass it to a function in the Enum module.

Let’s look at the below illustration:

Storing result using a stream

Streams build a series of computations that are invoked only when we pass the underlying stream to the Enum module. After that, we get the result stored in the stream.

Example

range = 1..5
stream = Stream.map(range, &(&1 * 2))
stream = Enum.map(stream, &(&1 + 1))
IO.puts("The Result of the Stream is as Follows")  
IO.inspect stream
Using composable stream

Explanation

  • Line 2: We define the range and map it on the stream using some operation &(&1 * 2).

  • Line 3: We again map the stream using enum and operation &(&1 + 1).

  • Line 5: We store the result in-stream and print it.

RELATED TAGS

elixir
stream

CONTRIBUTOR

Abdul Mateen
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring