我是 Kotlin 和协程的新手。我有一个fun
在我的活动及其内部,检查User
用户名和密码,如果为真,则返回Users
object.
一切都好。但是当我按下按钮时,我的活动被阻止并等待响应Users
login.
我用这个有趣的:
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?
}
这是我的 apiInterface:
interface WebApiService {
@GET("users/login")
suspend fun checkLogin(@Query("username") username: String,
@Query("password")password: String) : Users
如何解决等待从服务器检索数据时阻止我的活动的问题?