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?
CodePudding user response:
try this
suspend fun getEventById(eventId: Int): LiveData<Event> {
return withContext(Dispatchers.IO) {
eventRepository.getEventById(eventId)
}
}
CodePudding user response:
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.