我是Kotlin和协程的新手。在我的活动中有一个fun
,里面检查User
的用户名和密码,如果正确,则返回Users
对象。
一切都没问题。但是当我按下按钮时,我的活动会被阻塞并等待Users
登录的响应。
我使用了这个fun
:
private fun checkLogin() : Boolean {
runBlocking {
coroutineScope {
launch {
user = viewModel.getUserAsync(login_username.text.toString(), login_password.text.toString()).await()
}
}
if(user == null){
return@runBlocking false
}
return@runBlocking true
}
return false
}
这是我的 ViewModel:
class LoginViewModel(app: Application) : AndroidViewModel(app) {
val context: Context = app.applicationContext
private val userService = UsersService(context)
fun getUserAsync(username: String, password: String) = GlobalScope.async {
userService.checkLogin(username, password)
}
}
用户服务:
class UsersService(ctx: Context) : IUsersService {
private val db: Database = getDatabase(ctx)
private val api = WebApiService.create()
override fun insertUser(user: Users): Long {
return db.usersDao().insertUser(user)
}
override suspend fun checkLogin(username: String, pass: String): Users? {
return api.checkLogin(username, pass)
}
}
interface IUsersService {
fun insertUser(user: Users) : Long
suspend fun checkLogin(username: String, pass: String): Users?
}
这是我的 API 接口:
interface WebApiService {
@GET("users/login")
suspend fun checkLogin(@Query("username") username: String,
@Query("password")password: String) : Users
当等待从服务器检索数据时,我该如何解决阻止我的活动的问题?