首页 > 解决方案 > Squareup Retrofit/Moshi 示例进程未关闭

问题描述

我有一个适用于 Squareup 的 Retrofit2 http 客户端 ( https://square.github.io/retrofit/ ) 的“hello world”应用程序,使用 JSON 与 Moshi ( https://github.com/square/moshi ) 解组...

一切正常,但没有System.exit(0)应用程序将永远运行。

知道这是为什么吗?

import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path


fun main() {
    MainApp().doIt()
    println("main READY!")
    System.exit(0)
}

interface GitHubService {
    @GET("users/{user}/repos")
    fun listRepos(@Path("user") user: String): Call<List<Repo>>
}

@JsonClass(generateAdapter = true)
data class Repo(val full_name: String, val private: Boolean)

class MainApp {
    fun doIt() {
        val moshi = Moshi.Builder()
            .addLast(KotlinJsonAdapterFactory())
            .build()

        val retrofitGithub = Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()

        val githubService = retrofitGithub.create(GitHubService::class.java)

        val reposCall: Call<List<Repo>> = githubService.listRepos("HoffiMuc")

        val response = reposCall.execute()
        if (response.isSuccessful) {
            val repos = response.body() ?: ArrayList<Repo>()
            if ( repos.isNotEmpty() ) {
                for (repo in repos) {
                    println(repo)
                }
            } else {
                println("Response Body is null or no repo in result list")
            }
        } else {
            println(response.headers())
        }
    }
}

标签: kotlinretrofit2moshi

解决方案


如果您添加对最新版本的 OkHttp 的显式依赖会发生什么?旧版本 Retrofit 依赖于使用的非守护线程。


推荐阅读