android - 调用 REST API 的协程 -> 致命异常 : main

标签 android kotlin kotlin-coroutines

我需要从 REST API 获取一些数据,当我连接 4G 或 wifi 时一切正常,但当我处于飞行模式时,应用程序崩溃并显示:“E/AndroidRuntime:致命异常:main”

在此之前我有一个日志(不是错误提示:“跳过 1013 帧!应用程序可能在其主线程上做了太多工作。”)

所以我想在没有网络的情况下获取 API 会使应用程序崩溃,因为它在主线程中运行。但是我正在使用协程,对我来说,我做对了:

View 模型

private val viewModelJob = SupervisorJob()
private val viewModelScope = CoroutineScope(viewModelJob + Dispatchers.Main)
init {
        viewModelScope.launch {
            videosRepository.refreshVideos()
        }
    }

存储库

suspend fun refreshVideos() {
        withContext(Dispatchers.IO) {
            val playlist = Network.devbytes.getPlaylist().await()
            //database.videoDao().insertAll(*playlist.asDatabaseModel())
        }
    }

服务

/**
 * A retrofit service to fetch a devbyte playlist.
 */
interface DevbyteService {
    @GET("devbytes.json")
    fun getPlaylist(): Deferred<NetworkVideoContainer>
}

/**
 * Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
 * full Kotlin compatibility.
 */
private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

/**
 * Main entry point for network access. Call like `Network.devbytes.getPlaylist()`
 */
object Network {
    // Configure retrofit to parse JSON and use coroutines
    private val retrofit = Retrofit.Builder()
            .baseUrl("https://devbytes.udacity.com/")
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .build()

    val devbytes: DevbyteService = retrofit.create(DevbyteService::class.java)
}

所以完整的链是:

ViewModel -> 与 Dispatchers.Main 协程

调用存储库 -> 使用 Dispatchers.IO 启动协程的挂起函数

通过对象网络调用服务 ->,我得到一个带有返回延迟的 getPlaylist() 的改造实例,并且对该方法的调用在带有 await() 的存储库中

我做错了什么?

最佳答案

您的 API 调用抛出异常,因为没有网络连接(很可能是 UnknownHostException)。

将其包装在 try-catch 中并处理异常。

关于android - 调用 REST API 的协程 -> 致命异常 : main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58180265/

相关文章:

Java Lambda 到 Kotlin

kotlin - 如何在流中解构 Kotlin 对象

android - 从 Executor(ThreadPoolExecutor) 调用挂起协程的最佳方法

android - runInTransaction block 内的挂起方法

javascript - Android只能显示网站的一部分

android - 应用程序在后台时,哪些类型的数据可以被垃圾收集?

kotlin - 覆盖getValue和setValue以大写一对

android - 何时使用 withContext?

android - 如何将图像设置在与两个 TextView 相同的行上?

java - 错误和应用程序停止不幸的是,StrictMode.ThreadPolicy() 也不起作用