【发布时间】:2021-10-13 04:35:34
【问题描述】:
嘿,我想从 object 类调用 api。我是协程的新手。我尝试了一些代码,但我不确定它是否正确。
-
在LoginHelper里面有一个叫做logout的功能不止一个功能。我想先执行 api 调用。然后我想在注销中执行其他功能。
-
在 Mainactivity 我正在调用 LoginHelper.logout 它将完成然后我需要执行其他行。但我不想做暂停功能,因为它也在使用其他地方。
我也遇到了错误进程:
com.dimen.app, PID: 12496
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
Session.kt
interface Session{
@DELETE("/session/delete")
fun deleteSession(): Call<Void>
}
SessionRepository.kt
suspend fun deleteSession(): RequestResult<Void> {
return apiCall(api.deleteSession())
}
RequestResult 是一个Sealed Class
sealed class RequestResult<out T : Any> {
data class Success<out T : Any>(): RequestResult<T>
data class Error(): RequestResult<Nothing>()
fun result(success: (data: T?) -> Unit),error: (error: Error) -> Unit)
}
MainActivity.kt
private fun setupLogout() {
logoutButton.setOnClickListener {
LoginHelper.logout() // need to wait untill this finish
// more logic here....
}
}
LoginHelper.kt
object LoginHelper {
fun logout() {
logD("logout")
deleteSession() // need to wait untill this finish and then excute more function....
}
private fun deleteSession() {
runBlocking{
apiCall.deleteSession().execute()
}
}
}
【问题讨论】:
-
apiCall.deleteSession(it)究竟返回了什么? -
只有执行才会返回 Void
-
但它是什么类型的?它是否同步执行一项长期任务?
getToken()或deleteSession()是挂起函数吗? -
@Tenfour04
getToken是返回字符串的普通函数。deleteSession()是 api 调用并返回 RequestResult它是一个密封的类。 Sealed Class -
那么
apiCall.deleteSession()启动异步请求并立即返回?如果是这种情况,您根本不需要协程。
标签: android kotlin async-await kotlin-coroutines coroutine