Created
July 9, 2023 14:59
-
-
Save icanerdogan/b2699d4a83f20cca4a1c8db356e6ee54 to your computer and use it in GitHub Desktop.
Kotlin Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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