Complete guide to LiveData and Flow: Answering — Why, Where, When, and Which.

What is LiveData?.

What is Flow?

val flowOfNumbers = flow {
repeat(20) {
delay(3000)
emit(it)
}

}
viewModelScope.launch { 
flowOfNumbers.collect {
//collect numbers here


}
}
_flowNumberLiveData = repository.flowOfNumbers.asLiveData()
flowsNumnerLiveData.observe(viewLifecycleOwnner){ numbers -> })
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
appState.collect { appState ->
when(appState)
{
APPSTATE.LOADING ->
//green indicator somewhere in UI
APPSTATE.IDLE ->
//do not turn the indicator to green
}
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
appState.flowWithLifecycle(viewLifecycleOwner.lifecycle, Lifecycle.State.STARTED).collect { appState ->
when(appState)
{
APPSTATE.LOADING ->
//green indicator somewhere in UI
APPSTATE.IDLE ->
//do not turn the indicator to green
}
}
}
someMoviesLib?.addMoviewCallback { movies, _ ->
override fun onMoviesFetched(value: List<Movies>) {
//on shot movie lsit
}

override fun onApiError(cause: Throwable) {
}
}
fun getLocationUpdateSteam() = callbackFlow<Location> {
// A new Flow is created. This code executes in a coroutine!

// 1. Create callback and add elements into the flow
val callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
result ?: return // Ignore null responses
for (location in result.locations) {
try {
offer(location) // Send location to the flow
} catch (t: Throwable) {
// Location couldn't be sent to the flow
}
}
}
}

// 2. Register the callback to get location updates by calling requestLocationUpdates
requestLocationUpdates(
createLocationRequest(),
callback,
Looper.getMainLooper()
).addOnFailureListener { e ->
close(e) // in case of error, close the Flow
}

// 3. awaitClose will be executed when the flow is either closed or cancelled and hence its make sense removeLocationUpdates(callback) here
awaitClose {
// Clean up code goes here
removeLocationUpdates(callback)
}
}
public fun <T> flow(@BuilderInference block: suspend FlowCollector<T>.() -> Unit): Flow<T> = SafeFlow(block)
fun startFlow() : Flow<Int> = flow{
repeat(12)
{
delay(1000)
emit(i)
}
}
viewModelScope.launch {
startFlow().collect {
value -> println(value)
}
}
fun startFlow() : Flow<Int> = flow{
repeat(12)
{ emit(i)
}
}
viewModelScope.launch {
startFlow().collect {
delay(1000)
value -> println(value)
}
}
flow {
repeat(100) {
delay(3000)
Log.d("Flow", "***************************** ")
Log.d("Flow", "emitting = $it ")
emit(it)
}
Log.d("Flow", "emission done ")
}.shareIn(scope, SharingStarted.Eagerly,replay =1)
flow {
repeat(100) {
delay(3000)
Log.d("Flow", "***************************** ")
Log.d("Flow", "emitting = $it ")
emit(it)
}
Log.d("Flow", "emission done ")
}.stateIn(scope, SharingStarted.WhileSubscribed(), initialValue=1)
fun <T> Flow<T>.stateIn(
scope: CoroutineScope,
started: SharingStarted,
initialValue: T
): StateFlow<T> (source)
fun <T> Flow<T>.shareIn(
scope: CoroutineScope,
started: SharingStarted,
replay: Int = 0
): SharedFlow<T> (source)

--

--

--

Hi there 👋 Namaste 🙏🏻 .👨‍💻 developing apps from 10+ years. 👨‍🏫 IoT | E-commerce | baking domain expert.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Responsive Flutter UI using VelocityX

Jetpack Compose: How to play with Canvas?

How to preload images in Flutter ?

Easily build a Chronometer (a simple stopwatch)

What Matters Most to You? Here’s How to Find Out.

A glowing yellow question mark and a blue one in a pile of gray question marks.

6.6 Creating a Projection Matrix in Our Code

Now in Android #15

Part 1 A Simple Game of Air Hockey

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Balwinder Singh Rajput

Balwinder Singh Rajput

Hi there 👋 Namaste 🙏🏻 .👨‍💻 developing apps from 10+ years. 👨‍🏫 IoT | E-commerce | baking domain expert.

More from Medium

Sample Android project: MVVM Clean Architecture with Coroutines + Tips

Android interview prep 2022: Topics/concepts to master

Dealing with Multiple APIs via Retrofit? Learn How to use Sealed Classes Effectively

Android Modularization Preps: Things to know Before Modularizing Your App