Server.kt(是一个模拟服务器,它将返回用户列表) https://github.com/shalbert94/androidinterview/blob/master/server/src/main/java/com/jobrapp/server/Server.kt
由于某种原因,在我的存储库(https://github.com/shalbert94/androidinterview/blob/master/app/src/main/java/com/jobrapp/androidinterview/MockServerRepository.kt)中调用的val server = Server()
抛出:
Unable to start activity ComponentInfo{com.jobrapp.androidinterview/com.jobrapp.androidinterview.MainActivity}: android.os.NetworkOnMainThreadException
问题似乎源于调用MockWebServer()
的{{1}}块中调用的start()
的{{1}}方法。如何在不触发NetworkOnMainThreadException的情况下初始化存储库中的Server
?
答案 0 :(得分:0)
谢谢Kotlin协程!
fun getUsers(liveData: MutableLiveData<List<User>>) = launch {
val server = async{ Server() }
server.await().getUsers().enqueue(object: Callback<List<User>> {...})
}