项目作者: auron567

项目描述 :
Kotlin Coroutines StateFlow sample Android application
高级语言: Kotlin
项目地址: git://github.com/auron567/KotlinStateFlow.git
创建时间: 2020-05-23T17:11:08Z
项目社区:https://github.com/auron567/KotlinStateFlow

开源协议:

下载


Kotlin StateFlow

Sample Android application that show how can we use Kotlin Coroutines StateFlow.

Implementation

StateFlow is a new class introduced in version 1.3.6 of the Kotlin Coroutines library which works in the following way:

  • It’s a Flow with a single updatable data value that emits updates to the value to its collectors.
  • Updates to the value can be observed by collecting values from this flow.
  • It’s useful as a data-model class to represent any kind of state.
  • It’s designed to completely replace ConflatedBroadcastChannel in the future.




For example, the following class represents an integer state that increments its value by calling the method incrementCount:

  1. class CountModel {
  2. private val _countState = MutableStateFlow(0) // Private mutable state flow
  3. val countState: StateFlow<Int> get() = _countState // Public read-only state flow
  4. fun incrementCount() {
  5. _countState.value++
  6. }
  7. }

Now in a possible activity we can observe countState to keep track of its updates:

  1. lifecycleScope.launch {
  2. countModel.countState.collect { value ->
  3. countTextView.text = "$value"
  4. }
  5. }

This collector will be executed whenever the value of countState is updated. Also it’s lifecycle-aware as we’ve used it under lifecycleScope.

Libraries