Skip to content

Instantly share code, notes, and snippets.

@icanerdogan
Created July 9, 2023 14:59
Show Gist options
  • Save icanerdogan/b2699d4a83f20cca4a1c8db356e6ee54 to your computer and use it in GitHub Desktop.
Save icanerdogan/b2699d4a83f20cca4a1c8db356e6ee54 to your computer and use it in GitHub Desktop.
Kotlin Flow
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel : MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
CoroutineScope(Dispatchers.Main).launch {
viewModel.countDownTimerFlow.collect {
binding.textViewCounter.text = it.toString()
}
}
}
}
class MainViewModel : ViewModel() {
init {
collectInViewModel()
}
val countDownTimerFlow = flow<Int> {
val countDownFrom = 10
emit(countDownFrom)
var counter = countDownFrom
while (counter > 0) {
delay(1000)
counter--
emit(counter)
}
}
private fun collectInViewModel() {
CoroutineScope(Dispatchers.Main).launch {
countDownTimerFlow
.filter { it % 3 == 0 }
.map { it * it }
.collect { println("Counter is $it") }
/*
countDownTimerFlow.collectLatest {
// delay(2000)
println("Counter is $it")
}
*/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment