Use case – streaming data

Recently, I was faced with a relatively simple programming task: querying 10 content indexers for a specific keyword, and then displaying the results of the search to the user. A valid first approach would have been to launch a coroutine for each content indexer, returning Deferred<List<ResultDto>>, and upon completion of all of the coroutines, merging the results and sending them to the UI.

A representation of this approach could look like this:

In this example, search() starts three coroutines, giving them the keywords to search. Each coroutine will fetch the results from the indexer. Upon completion of the three coroutines, search() will compile and return the results.

The problem with this approach is that each indexer will take a different amount of time to return a response, and some of them may take considerably longer. So, having to wait for all of the coroutines to complete will delay the UI from displaying results, thus preventing the user from interacting with results as soon as they become available.

A better solution requires a couple of changes to be made. First, we want search() to return a Channel<ResultDto>—as we will see later in the chapter, ReceiveChannel<ResultDto> is the best option— this way the results can be sent to the UI as soon as they arrive. Second, we want search() to be able to seamlessly receive the results from each coroutine as they arrive as well.

To accomplish this, each coroutine will send results through a single channel as they retrieve and process the response. Meanwhile, search() will simply return the channel so that the caller can process the results at their convenience.

It would look something like this:

This way, the caller will receive the results as they are obtained from the content indexer, and the UI will be able to display the results incrementally, allowing the user to interact with them as soon as they are available, for a fluid and fast experience.

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

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