Integrating Coroutines in Android can significantly simplify asynchronous programming. By leveraging the power of Kotlin Coroutines, you can work smoothly with Android components such as Activities, Fragments, and ViewModels. Below, we provide a comprehensive example of how to implement Coroutines in conjunction with a ViewModel.
// ViewModel class
class MyViewModel : ViewModel() {
private val _data = MutableLiveData()
val data: LiveData get() = _data
fun fetchData() {
viewModelScope.launch {
// Simulate a network call
val result = fetchDataFromNetwork()
_data.value = result
}
}
private suspend fun fetchDataFromNetwork(): String {
delay(1000) // Simulating network delay
return "Data from network"
}
}
// Activity class
class MyActivity : AppCompatActivity() {
private lateinit var viewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.data.observe(this, Observer { data ->
// Update UI
textView.text = data
})
// Fetch data
viewModel.fetchData()
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?