implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0")
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val second = findViewById<Button>(R.id.goToSecond)
second.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
Log.d("TEST", "START")
CoroutineScope(Dispatchers.IO).launch {
a()
b()
}
Log.d("TEST", "END?")
}
suspend fun a() {
delay(1000)
Log.d("TEST", "AP1")
delay(1000)
Log.d("TEST", "AP2")
}
suspend fun b(){
delay(1000)
Log.d("TEST", "BP1")
delay(1000)
Log.d("TEST", "BP2")
}
}
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1")
class SecondActivity : AppCompatActivity() {
lateinit var viewModel: SecondViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
viewModel = ViewModelProvider(this).get(SecondViewModel::class.java)
val secondBtn = findViewById<Button>(R.id.secondBtn)
secondBtn.setOnClickListener {
viewModel.a()
viewModel.b()
}
}
}
class SecondViewModel : ViewModel() {
fun a() {
CoroutineScope(Dispatchers.IO).launch{
for(i in 0..10){
delay(1000)
Log.d("SecondViewModel A", i.toString())
}
}
}
fun b() {
viewModelScope.launch{
for(i in 0..10){
delay(1000)
Log.d("SecondViewModel B", i.toString())
}
}
}
}
'Android Jetpack' 카테고리의 다른 글
Retrofit Simple Example RecyclerView 추가 (0) | 2022.04.18 |
---|---|
기존 예제 변경 (0) | 2022.04.17 |
ViewModelScope (0) | 2022.04.13 |
Retrofit이란? (0) | 2022.04.12 |
ViewModelScope (0) | 2022.04.11 |