Search code examples
androidokhttpandroid-mvvmmockwebserver

How to initialize okHttp's MockServer() in a repository?


Server.kt (is a mock server that will return a list of Users) https://github.com/shalbert94/androidinterview/blob/master/server/src/main/java/com/jobrapp/server/Server.kt

For some reason, val server = Server() called in my repository (https://github.com/shalbert94/androidinterview/blob/master/app/src/main/java/com/jobrapp/androidinterview/MockServerRepository.kt) throws: Unable to start activity ComponentInfo{com.jobrapp.androidinterview/com.jobrapp.androidinterview.MainActivity}: android.os.NetworkOnMainThreadException

The issue seems to stem from calling MockWebServer()'s start() method which is called in Server's init block. How can I initialize Server in my repository without triggering a NetworkOnMainThreadException?


Solution

  • Thank you Kotlin coroutines!

    fun getUsers(liveData: MutableLiveData<List<User>>) = launch {
            val server = async{ Server() }
    
            server.await().getUsers().enqueue(object: Callback<List<User>> {...})
        }