For Korlin
In case of coroutineScope.launch(Dispatchers.Main) {}
you may run into a problem Suspend function '...' should be called only from a coroutine or another suspend function
.
I found the following way
private var queryTextChangedJob: Job? = null
private lateinit var searchText: String
Next don't forget use implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha05"
override fun onQueryTextChange(newText: String?): Boolean {
val text = newText ?: return false
searchText = text
queryTextChangedJob?.cancel()
queryTextChangedJob = lifecycleScope.launch(Dispatchers.Main) {
println("async work started...")
delay(2000)
doSearch()
println("async work done!")
}
return false
}
If you want use launch
inside ViewModel then use implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha05"
queryTextChangedJob = viewModelScope.launch(Dispatchers.Main) {
//...
}