Android Kotlin Flows: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 30: Line 30:
</syntaxhighlight>
</syntaxhighlight>
We can use collectLatest which will only output the latest state
We can use collectLatest which will only output the latest state
=Flow Operators=
Like RxJava there are a billion operators. Here is filter.
<syntaxhighlight lang="kotlin">
    private fun collectFlow() {
        viewModelScope.launch {
            countDownFlow.filter {time ->
                time % 2 == 0
            }.collect { time ->
                println("Time Remaining: $time")
            }
        }
    }
</syntaxhighlight>
Popular ones covered in the video are
*Filter
*Map
*OnEach (for debugging, forgotten the one for RxJava)
Terminal Flow Operators
*count (at the end)
*reduce
*fold (Same as Reduce with an initial value)
Flattening Operarors
*flatMap
*flatMapConcat
*flatmapMerge
<syntaxhighlight lang="kotlin">
</syntaxhighlight>

Revision as of 02:23, 18 March 2025

Introduction

This is a page to capture anything important about kotlin flows. This very similar to RxJava

Simple Example

Note this code would not be executed, if there are no subscribers like RxJava

 
  val countDownFlow = flow<Int> {
    val startingValue = 10
    var currentValue = startingValue
    emit(currentValue)
    while (currentValue > 0) {
      delay(1000L)
      currentValue--
      emit(currentValue)
    }
  }

We can log our emits in the ViewModel to debug with

 
    init {
        collectFlow()
    }

    private fun collectFlow() {
        viewModelScope.launch {
            countDownFlow.collect { time ->
                println("Time remaining: $time")
            }
        }
    }

We can use collectLatest which will only output the latest state

Flow Operators

Like RxJava there are a billion operators. Here is filter.

 
    private fun collectFlow() {
        viewModelScope.launch {
            countDownFlow.filter {time ->
                time % 2 == 0
            }.collect { time ->
                println("Time Remaining: $time")
            }
        }
    }

Popular ones covered in the video are

  • Filter
  • Map
  • OnEach (for debugging, forgotten the one for RxJava)

Terminal Flow Operators

  • count (at the end)
  • reduce
  • fold (Same as Reduce with an initial value)

Flattening Operarors

  • flatMap
  • flatMapConcat
  • flatmapMerge