Android Kotlin Flows: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 3: Line 3:
=Simple Example=
=Simple Example=
<syntaxhighlight lang="kotlin">  
<syntaxhighlight lang="kotlin">  
fun fred() {
   val countDownFlow = flow<Int> {
   val countDownFlow = flow<Int> {
     val startingValue = 10
     val startingValue = 10
Line 14: Line 13:
     }
     }
   }
   }
}
</syntaxhighlight>
</syntaxhighlight>
We can log our emits in the ViewModel to debug with
<syntaxhighlight lang="kotlin">
    init {
        collectFlow()
    }
    private fun collectFlow() {
        viewModelScope.launch {
            countDownFlow.collect { time ->
                println("Time remaining: $time")
            }
        }
    }
</syntaxhighlight>
We can use collectLatest which will only output the latest state

Revision as of 02:04, 18 March 2025

Introduction

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

Simple Example

 
  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