You can either switch dispatcher contexts (Dispatchers.IO for the logic, then to Dispatchers.Main for updating the UI), or you can move your code into a ViewModel and there use the same context switching technique or use postvalue() of LiveData. An example of doing the latter below. You can read on ViewModel here: https://developer.android.com/topic/libraries/architecture/viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MyViewModel() : ViewModel() {
private val files: MutableLiveData<List<String>> by lazy {
MutableLiveData<List<String>>()
}
fun loadFiles(path: String) {
viewModelScope.launch(){
doLoadFiles()
}
}
private suspend fun doLoadFiles() {
withContext(Dispatchers.IO) {
val results = listOf("patha", "pathb")//replace with your actual code
files.postValue(results)
}
}
fun getFiles(): LiveData<List<String>> = files
}
Then call it like this from your activity
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val model = ViewModelProviders.of(this)[MyViewModel::class.java]
model.getFiles().observe(this, Observer<List<String>>{ paths ->
// update UI
println (paths)
})
model.loadFiles("S")
}
In your build.gradle file, make sure to import the relevant dependencies
def lifecycle_ver = "2.2.0-rc02"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_ver"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_ver"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_ver"
withContext(Dispatchers.Main){}