Basics of Kotlin Flow
Basics of Kotlin Flow
What is a Flow?
Reactive Programming
Flow Builders
Flow Operators
Lifecycle Operators
Terminal Operators
Intermediate Operators
What is a Flow?
What is a Flow?
“a stream of values
that are computed asynchronously”
What is a Flow?
“a stream of values
that are computed asynchronously”
asynchronous data stream
Converting a function that returns a single value to an
asynchronous data stream
return type # of return values when characteristic
BigInteger single value once blocking
List<BigInteger> multiple values once blocking
Sequence<BigInteger> multiple values continuously blocking and synchronous
suspending and
Flow<BigInteger> multiple values continuously
asynchronous
Suspend function
VS
Flow
Reactive
Programming
Observer
Pattern
LiveData
Activity observe LiveData property
ViewModel
& react to changes
Room
DB
Reactive Approach Imperative Approach
Expose a Flow Expose a Suspend Function
other components can subscribe &
other components need to periodically
receive changes check for data changes
First
Kotlin Flow
Usecase
ViewModel
mocked
Endpoint
Activity ViewModel
ViewModel Flow<Stock>
LiveData<UiState>
DataSource
renders UI
Flow Builders
Basic Flow Builders
Flow Builder Description Example
owOf() create a Flow from a xed set of values flowOf(1,2,3)
listOf("A", "B", "C")
.asFlow() extension function on various types to convert them into Flows
.asFlow()
flow {
builder function to construct arbitrary ows
emit("one")
ow{} delay(100)
from sequential calls to the emit function emit("two")
}
fl
fl
fi
fl
Terminal
Operators
Terminal Operators
collect { }
first()
last()
single()
toList(), toSet()
fold(), reduce()
Terminal operator
launchIn()
Lifecycle
operators
Terminal operator
.asLiveData()
Basic
Intermediate
Operators
Basics of Kotlin Flow
Recap 🎓
What is a Flow?
“a stream of values
that are computed asynchronously”
Flow Builder
Basic Flow Builders
Flow Builder Description Example
owOf() create a Flow from a xed set of values flowOf(1,2,3)
listOf("A", "B", "C")
.asFlow() extension function on various types to convert them into Flows
.asFlow()
flow {
builder function to construct arbitrary ows
emit("one")
ow{} delay(100)
from sequential calls to the emit function emit("two")
}
fl
fl
fi
fl
Lifecycle Operator
Lifecycle Operators
onStart{}
onCompleted{}
Terminal Operator
Terminal Operators
collect{}
first(), last(), single()
toList(), toSet()
launchIn()
asLiveData()
Intermediate
Operator
Basic Intermediate Operators
map{}
filter{}
take(), drop()
transform{}
withIndex()
distinctUntilChanged()