Suspendable sequences and iterators

So far, we have discussed and implemented suspending functions in one way: as functions that suspend while waiting for the execution of one or more computations to happen. A simple representation of this is as follows:

In this example, getProfile starts its execution and, soon after, it suspends to wait for fetchProfile to execute. Once the response has been processed, getProfile suspends once more, this time to call calculateAge. When calculateAge finishes, the execution of getProfile continues until completion.

In this chapter, we will cover a different scenario: writing functions that are suspended between executions. For example, we can have a repository that is suspended until the next page is required:

In the previous example, the next() function will yield the first element from the data source, and will suspend immediately after returning it. Whenever next() is called again, the execution will be resumed until a value is yielded, and then the function will suspend once more.

We will start by taking a look at suspendable sequences and suspendable iterators. Both of them share a few important characteristics:

  • While they suspend between invocations, they can't be suspended during execution. Because of this, it's possible to iterate on them without having to be in a suspending computation.
  • Their builders don't receive a CoroutineContext. This means that by default their code will be executed on the same context that they are invoked in.
  • They can only suspend after yielding information. For this to happen, the yield() or yieldAll() function must be invoked.

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

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