đź‘ŹKotlin (over) Flow review đź‘Ź

Costa Fotiadis
3 min readOct 18, 2020

Flow is fun to play around with.

In short, it represents a cold stream of values. Kind of like my typical afternoon drinking a stream of too many cold ones.

Aside from looking at memes all day we might as well write some code.

FlowGuy holds this stream that will emit a new list containing humans every 1 second.

All this work will happen on the IO thread/scheduler/whatever, just to be safe and keep the UI thread free.

Since this is a cold stream, nothing is actually happening when we run our app until someone starts collecting this someFlow variable.

Am I flowing yet?

This seems fairly standard but the editor will complain:

This flow could take a while and it would be awful to have a memory leak. Let’s use the classic viewModelScope then.

shameless plug to the best way of (un)learning coroutines:

Kotlin Coroutines Review

shame 🔔🔔

Since this flow is returning a list of humans, it would be nice to see the results of this happening in real-time with a nice adapter-recyclerview combo.

A fragment with a button and said recyclerview should do it.

  • Get an adapter-recycler ready then observe for changes in the livedata variable that the ViewModel holds.
    Once a change has been observed we pass the whole thing into the adapter
  • A button will trigger the start of the flow.

Title here

Let’s try this out!

That’s it. You are free to go watch YouTube now.

Hol’ up!

There is something very fishy with this example.

A flow can take milliseconds to complete, or it can take minutes/hours as in the example above. Maybe it will never “really” complete.

Room, for instance, provides observable reads with Flow enabling you to get notified of changes in your database.

Launching a collection from the click of a button, or any 1-shot operation that can be repeated, suddenly doesn’t sound like a great idea.

Case in point when clicking the START button many times.

Running a collect multiple times will not stop the previous collections that are in progress.

What now?

Returning to the original issue- it is fixed easily by keeping a reference to the coroutine/Job and cancelling it before running a collection.

In the event you are interested in only collecting a few values from a stream then there’s a handy operator for that- take(number) .

Source code can be found here.

Later.

--

--