Get user by userId in ROOM

Viewed 53

I want to take event by id but it returns unit.

Entity:

@Dao
interface EventDao {
    @Query("SELECT * FROM event_table WHERE eventId= :myeventId")
    fun getEventByEventId(myeventId: Int): LiveData<Event>
}

Repository:

class EventRepository(private val eventDao: EventDao){
    fun getEventById(myeventId: Int): LiveData<Event>{
            return eventDao.getEventByEventId(myeventId = myeventId)
    }
}

Viewmodel:

class EventViewModel (application: Application): AndroidViewModel(application) {
 private val readEventById = MutableLiveData<LiveData<Event>>()
fun getEventById(eventId: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            readEventById.postValue(eventRepository.getEventById(eventId))
        }
    }
}

I am calling it on user fragment:

lifecycleScope.launch {
        val event = eventViewModel.getEventById(currentUserId)
    }

but it returns unit. How can i return event by userId?

2 Answers

In your ViewModel class, you should include a public LiveData<Event> value that returns the readEventById live data object:

val selectedEvent: LiveData<Event>
    get() = readEventById

Then, in the user Fragment, you should instead add an Observer on eventViewModel.selectedEvent. When you call eventViewModel.getEventById(currentUserId), you don't worry about the result. Instead, the Observer will let you know the LiveData<Event> was updated and you can handle the value this way.

This is the proper approach since you're getting the data from the database asynchronously.

We can use withContext for returning values from a coroutine scope, it is defination from documentation : "Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result." for details visit the documentation withContext

in your case you can use like this

suspend fun getEventById(eventId: Int): LiveData<Event> {
    return withContext(Dispatchers.IO) {
        eventRepository.getEventById(eventId)
    }
}
Related