我试图在Android中使用WorkManager
,因为到目前为止,我已经使用AsyncTask
完成了插入更新。
我正在尝试更新Room database
中的用户。我已经在Repository
中创建了一个类以在后台执行该过程,但是我不知道这是否是正确的编码方式。我也有点困惑如何在userViewModel中调用方法。
这是我的代码:
在存储库中:
inner class Test(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
override fun doWork(): Result {
fun updateUser(userId : Int , userName :String , userLastname: String){
userDao.updateUser(userId, userName, userLastname)
}
return Result.success()
}
}
在viewModel中:
private val workManager: WorkManager = WorkManager.getInstance()
fun updateUser(userID: Int, userName: String, userLastname: String) {
workManager.enqueue(OneTimeWorkRequest.from(Repository.Test::class.java))
}
也许这不是使用WorkManager的正确方法,所以如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:1)
您可以对代码进行较小的更改。您可以使用WorkManager
类将诸如userId,userName等的参数传递给Data
。同样,也不需要使Worker
类成为内部类。只需将其设为独立的类即可。因此,worker
类基本上看起来像:
TestWorker.kt
class TestWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
override fun doWork(): Result {
val userId = inputData.getInt("USER_ID")
val userName = inputData.getString("USER_NAME")
val userLastname = inputData.getString("USER_LAST_NAME")
AppDatabase.getInstance().userDao.updateUser(userId, userName, userLastname)
return Result.success()
}
}
TestViewModel.kt
class TestViewModel : ViewModel() {
fun updateUser(userId: Int, userName: String, userLastName: String) {
val worker = OneTimeWorkRequest.Builder(TestWorker::class.java)
val data = Data.Builder()
//Add parameter in Data class. just like bundle. You can also add Boolean and Number in parameter.
data.putInt("USER_ID", userId)
data.putString("USER_NAME", userName)
data.putString("USER_LAST_NAME", userLastName)
//Set Input Data
worker.setInputData(data.build())
//enque worker
WorkManager.getInstance().enqueue(worker.build())
}
}
别忘了让您的数据库像这样:
@Database(entities = [User::class],
version = 1,
exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
// For Singleton instantiation
@Volatile
private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context, AppDatabase::class.java, "userdb")
.build()
}
}