0

I use Kotlin Flow and LiveData to fetch objects from room database. I want to know that the value of the object in the database has changed. I did the following;

UserDao

@Query("SELECT * FROM user WHERE id=:userId")
fun getUserById(userId: String?) : Flow<User>

UserRepository

fun getUserById(userId: String?) : Flow<User> = userDao.getUserById(userId);

ViewModel

val userId = MutableStateFlow<String>("")

val user : LiveData<User> = userId.flatMapLatest { id ->
    userRepository.getUserById(id)
}.asLiveData()

There is no problem while fetching the data but when I change the user's name, the "user.name" value is not updated.

Note: Changing in database, checked.

I update the name as follows:

@Query("UPDATE user SET name = :name WHERE id = :userId")
suspend fun updateName(name: String, userId: String)
Pehr Sibusiso
  • 862
  • 1
  • 14
  • 27
  • can you provide the code for updating the name? – Sami Shorman Mar 01 '21 at 07:23
  • @SamiShorman Can you check my update? – Pehr Sibusiso Mar 01 '21 at 17:44
  • and how u call updateName() from ui, and why u don't use @Update annotation in room and pass the new user object to the function , i will submit as answer maybe it will help. – Sami Shorman Mar 01 '21 at 18:29
  • @MuratAKSU do you ping `userId` object while updating the database. Otherwise I don't think `upstream` will be triggered and deliver data to `downstream`. I didn't understand the flow here. – nuhkoca Mar 01 '21 at 20:49

1 Answers1

0

u can use this to achieve what you want:

in Doa:

@Update
suspend fun updateUser(user:User)

and in ui:

user.name = newName
updateUser(user)

I know that's not the way u want, but it can give you same behavior, thank you.

Sami Shorman
  • 149
  • 1
  • 11