I am trying to understand how coroutines work
with bellow code, the UI is not freezing
<code>override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
delay(1000)
}
}
}
</code>
<code>override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
delay(1000)
}
}
}
</code>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
delay(1000)
}
}
}
But with bellow code, the UI is freezing
<code>override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
myOwnDelayCode()
}
}
}
suspend fun myOwnDelayCode() {
val date = System.currentTimeMillis()
while(System.currentTimeMillis() - date < 1000) {}
}
</code>
<code>override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
myOwnDelayCode()
}
}
}
suspend fun myOwnDelayCode() {
val date = System.currentTimeMillis()
while(System.currentTimeMillis() - date < 1000) {}
}
</code>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val scope = CoroutineScope(Dispatchers.Main)
binding.root.setOnClickListener {
scope.launch {
myOwnDelayCode()
}
}
}
suspend fun myOwnDelayCode() {
val date = System.currentTimeMillis()
while(System.currentTimeMillis() - date < 1000) {}
}
Why does it happen eventhough i put “suspend” to my function?