Whenever i call one of the getNotes() method in my fragment the obsever is not updating the data. It is however updating is if i go from mainfragment to other fragment and back to mainfragment again...
I don't know what is wrong. Here i am new to livedata please help
class MainViewModel #ViewModelInject constructor(
val repository: NoteRepository
): ViewModel() {
var notes: LiveData<List<Note>>
init {
notes= repository.getAllNotes()
}
fun getNotes(){
notes = repository.getAllNotes()
}
fun getFavoriteNotes(){
notes = repository.getAllNotesFavoriteOrder()
}
fun searchNotes(searchString:String){
notes = repository.getAllNotesQueryTitle(searchString)
mainViewModel.notes.observe(viewLifecycleOwner){
adapter.setData(it)
}
class NoteRepository #Inject constructor (val noteDao: NoteDao) {
suspend fun insertNote(note: Note){
noteDao.insertNote(note)
}
fun getAllNotes():LiveData<List<Note>>{
return noteDao.getAllNotes()
}
fun getAllNotesFavoriteOrder():LiveData<List<Note>>{
return noteDao.getAllNotesFavoriteOrder()
}
fun getAllNotesQueryTitle(searchString : String) : LiveData<List<Note>> {
return noteDao.getAllNotesQueryTitle(searchString)
}
suspend fun deleteAllNotes(){
noteDao.deleteAllNotes()
}
suspend fun deleteNote(note: Note){
noteDao.deleteNote(note)
}
suspend fun updateNote(note: Note){
noteDao.updateNote(note)
}
}
LiveData should be stored in a read-only val property. You keep assigning your read-write var property to point at other LiveData instances, so you are not updating the LiveData instance that you are initially observing.
You do need to make the property of type MutableLiveData so you can actually update it:
val notes = MutableLiveData<List<Note>>()
init {
getNotes()
}
The functions in NoteRepository should be returning Lists, not LiveData<List>s.
In your ViewModel, when you retrieve a list from the repo, assign it to the LiveData's value property, for example:
fun getNotes(){
notes.value = repository.getAllNotes()
}
A safer pattern is to make your MutableLiveData property private, and exposing a public LiveData version of it, so external classes cannot modify it:
private val _notes = MutableLiveData<List<Note>>()
val notes: LiveData<List<Note>> get() = _notes
//...
fun getNotes(){
_notes.value = repository.getAllNotes()
}
I suggest changing the function names getNotes() and getFavoriteNotes() to something like retrieveNotes(). Function names that start with get look like Java beans or the equivalent of Kotlin properties, so those names are misleading because the functions don't return anything.
Related
I get page data from a database, I have a repository that returns a flow.
class RepositoryImpl (private val db: AppDatabase) : Repository {
override fun fetchData (page: Int) = flow {
emit(db.getData(page))
}
}
In the ViewModel, I call the stateIn(), the first page arrives, but then how to request the second page? By calling fetchData(page = 2) I get a new flow, and I need the data to arrive on the old flow.
class ViewModel(private val repository: Repository) : ViewModel() {
val dataFlow = repository.fetchData(page = 1).stateIn(viewModelScope, WhileSubscribed())
}
How to get the second page in dataFlow?
I don't see the reason to use a flow in the repository if you are emitting only one value. I would change it to a suspend function, and in the ViewModel I would update a variable of type MutableStateFlow with the new value. The sample code could look like the following:
class RepositoryImpl (private val db: AppDatabase) : Repository {
override suspend fun fetchData (page: Int): List<Data> {
return db.getData(page)
}
}
class ViewModel(private val repository: Repository) : ViewModel() {
val _dataFlow = MutableStateFlow<List<Data>>(emptyList())
val dataFlow = _dataFlow.asStateFlow()
fun fetchData (page: Int): List<Data> {
viewModelScope.launch {
_dataFlow.value = repository.fetchData(page)
}
}
}
LeakCanary is telling me that one of my ViewModels is leaking but after playing around for 2 days I can't get the leak to go away.
Here is why LeakCanary shows
Here is the Fragment getting the ViewModel
viewModel = ViewModelProvider(this).get(ViewBreederViewModel::class.java).apply {
getStrains(arguments?.getString(BREEDER_ID_KEY, "")!!)
}
Here is the ViewModel
class ViewBreederViewModel(application: Application) : AndroidViewModel(application) {
private val breederRepository = BreederRepository(application)
val strainList = MutableLiveData<List<MinimalStrain>>()
fun getStrains(breederId: String) {
viewModelScope.launch {
breederRepository.getMinimalStrains(breederId).observeForever {
strainList.value = it
}
}
}
}
Here is the BreederRepository:
class BreederRepository(context: Context) {
private val dao: BreederDao
private val breederApi = RetrofitClientInstance.getInstance(context).breederAndStrainIdsApi
init {
val database: Db = Db.getInstance(
context
)!!
dao = database.breederDao()
}
suspend fun getMinimalStrains(breederId: String): LiveData<List<MinimalStrain>> =
withContext(Dispatchers.IO) {
dao.getMinimalStrains(breederId)
}
}
Here is the Db class
#Database(
entities = [Breeder::class, Strain::class],
version = 1,
exportSchema = true)
#TypeConverters(RoomDateConverter::class)
abstract class Db : RoomDatabase() {
abstract fun breederDao(): BreederDao
companion object {
private var instance: Db? = null
#JvmStatic
fun getInstance(context: Context): Db? {
if (instance == null) {
synchronized(Db::class) {
instance = Room.databaseBuilder(
context.applicationContext,
Db::class.java, "seedfinder_db"
)
.build()
}
}
return instance
}
}
}
You're using observeForever, which, as the name suggest, will keep observing forever, even after your ViewModel is cleared. Room does not require using a suspend method for DAO methods that return a LiveData and that is never the right approach in any case - LiveData is already asynchronous.
Instead, you should be transforming your LiveData, using your breederId as the input to your strainList LiveData:
class ViewBreederViewModel(application: Application) : AndroidViewModel(application) {
private val breederRepository = BreederRepository(application)
private val currentBreederId = MutableLiveData<String>()
// Here we use the switchMap method from the lifecycle-livedata-ktx artifact
val strainList: LiveData<String> = currentBreederId.switchMap {
breederId -> breederRepository.getMinimalStrains(breederId)
}
private fun setBreederId(breederId: String) {
currentBreederId.value = breederId
}
}
Where your getMinimalStrains becomes:
fun getMinimalStrains(breederId: String): LiveData<List<MinimalStrain>> =
dao.getMinimalStrains(breederId)
And you use it by setting your breederId in your UI and observing your strainList as before:
viewModel = ViewModelProvider(this).get(ViewBreederViewModel::class.java).apply {
setBreederId(arguments?.getString(BREEDER_ID_KEY, "")!!)
}
viewModel.strainList.observe(viewLifecycleOwner) { strainList ->
// use your updated list
}
If you're using Saved State module for ViewModels (which is the default if you're using the latest stable Fragments / Activity libraries), then you can use SavedStateHandle, which is automatically populated from your Fragment's arguments and skip the setBreederId() entirely:
class ViewBreederViewModel(
application: Application,
savedStateHandle: SavedStateHandle
) : AndroidViewModel(application) {
private val breederRepository = BreederRepository(application)
// Here we use the switchMap method from the lifecycle-livedata-ktx artifact
val strainList: LiveData<String> = savedStateHandle
.getLiveData(BREEDER_ID_KEY) // Automatically populated from arguments
.switchMap {
breederId -> breederRepository.getMinimalStrains(breederId)
}
}
Which means your code can simply become:
viewModel = ViewModelProvider(this).get(ViewBreederViewModel::class.java)
viewModel.strainList.observe(viewLifecycleOwner) { strainList ->
// use your updated list
}
And if you use the fragment-ktx artifact, you can simplify this further to:
// Move this to where you declare viewModel
val viewModel: ViewBreederViewModel by viewModels()
viewModel.strainList.observe(viewLifecycleOwner) { strainList ->
// use your updated list
}
I have an abstract class, with a MediatorLiveData object in it. This object has a number of sources, one of which depends on the childs class, and is abstract in the parent class.
Adding the sources in an init block causes a NullPointerException at runtime, because at the time the init block adds the source, it is still abstract (or so I have been led to believe).
Is there a way to use an abstract LiveData as a source for a MediatorLiveData without having to set that source in a child class? I just want to override val and be done with it, since I definitely will forget to call the addSources() function at some time in the future.
(I am aware that this example is not the most useful way to do this exact thing, but I didn't want to add unneccesary complexity)
Example:
abstract class MyClass: ViewModel(){
private val _myMediator = MediatorLiveData<String>()
protected abstract val mySource: LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
// This will cause a NullPointerException at runtime
init{
_myMediator.addSource(mySource){ _myMediator.value = it }
}
//This should work, but requires this to be called in child class
protected fun addSources(){
_myMediator.addSource(mySource){ _myMediator.value = it }
}
}
class myChild: MyClass(){
override val mySource = Transformations.map(myRepository.someData) { it.toString() }
// This is where init { addSources() } would be called
}
After reading Stachu's anwser, I decided to go with this, which I didn't test butI think should work:
abstract class MyFixedClass: ViewModel(){
private val _myMediator: MediatorLiveData<String> by lazy{
MediatorLiveData<String>().apply{
addSource(mySource){ this.value = it }
}
}
protected abstract val mySource: LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
}
class MyChild: MyFixedClass(){
override val mySource = Transformations.map(myRepository.someData) { it.toString() }
}
how about using lazy evaluation, e.g. something like this
abstract class MyClass : ViewModel() {
private val _myMediator = MediatorLiveData<String>()
private val _mySource: LiveData<String> by lazy { mySource() }
protected abstract fun mySource(): LiveData<String>
val myObservable: LiveData<String>
get() = _myMediator
init {
_myMediator.addSource(_mySource) { _myMediator.value = it }
}
}
class myChild : MyClass() {
override fun mySource() = Transformations.map(myRepository.someData) { it.toString() }
}
Working with Androind and Room for the first time, and i was able to follow a few codelabs and tutorials to achieve inserting and showing a list of my entities, but i cant seem to be able to use my other Repository methods in my ViewModel due to a type mismatch, here is my ViewModel file
class CustomerViewModel(application: Application) : AndroidViewModel(application) {
// The ViewModel maintains a reference to the repository to get data.
private val repository: CustomerRepository
// LiveData gives us updated words when they change.
val allCustomers: LiveData<List<Customer>>
init {
// Gets reference to Dao from db to construct
// the correct repo.
val customerDao = AppDatabase.getInstance(application).customerDao()
repository = CustomerRepository(customerDao)
allCustomers = repository.getCustomers()
}
fun insert(customer: Customer) = viewModelScope.launch {
repository.insert(customer)
}
}
and im trying to add a method like
fun find(id: Int) = viewModelScope.launch {
return repository.getCustomerByLocalId(id)
}
but the ide says there's a type mismatch here? Required: Customer, Found: Job
here is my repository:
class CustomerRepository(private val customerDao: CustomerDao) {
fun getCustomers(): LiveData<List<Customer>> = customerDao.getAlphabetizedCustomers()
suspend fun getCustomerByLocalId(local_Id: Int): Customer =
customerDao.customerByLocalId(local_Id)
suspend fun insert(customer: Customer) {
customerDao.insert(customer)
}
companion object {
// For Singleton instantiation
#Volatile
private var instance: CustomerRepository? = null
fun getInstance(customerDao: CustomerDao) =
instance ?: synchronized(this) {
instance ?: CustomerRepository(customerDao).also { instance = it }
}
}
}
methods in CustomerDao
#Query("SELECT * from customers ORDER BY name ASC")
fun getAlphabetizedCustomers(): LiveData<List<Customer>>
#Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(customer: Customer)
#Query("SELECT * FROM customers WHERE local_id = :localId")
suspend fun customerByLocalId(localId: Int): Customer
EDIT
I tried #lena-bru 's suggestion but the error is still there, there appears to be 2 different ones, the type mismatch and that there should not be a return. are you supposed to create this method in a different location?
The IDE error
change this:
fun find(id: Int) = viewModelScope.launch {
return repository.getCustomerByLocalId(id)
}
to this:
fun find(id: Int): Customer = viewModelScope.launch {
withContext(Dispatchers.IO){
repository.getCustomerByLocalId(id)
}
}
Your find method as defined above is void, it needs to return type Customer
Also you need to provide a context, and remove the return keyword
I'm rewriting an app that involves retrieving data from a server via REST, saving that to the database on each Android device, and then displaying that data to the user. The data being retrieved from the server has a "since" parameter, so it won't return all data, just data that has changed since the last retrieval.
I have the retrieval from the server working fine, but I'm not sure the best way to save that data to the database, then show it to the user. I'm using Kotlin, Retrofit, Room and LiveData.
The code below is a simplified version of what I'm actually doing, but it gets the point across.
MyData.kt (model)
#Entity(tableName = "MyTable")
data class MyData(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "id")
var id Int? = null,
#SerializedName("message")
#ColumnInfo(name = "message")
var message: String? = null
) {
companion object {
fun fromContentValues(values: ContentValues): MyData {
val data = MyData()
// Do this for id and message
if (values.containsKey("id") {
data.id = values.getAsInteger("id")
}
}
}
}
DataViewModel.kt
class DataViewModel(application: Application) : AndroidViewModel(application) {
private val repository = DataRepository()
fun data(since: Long) =
liveData(Dispatchers.IO) {
val data = repository.getDataFromServer(since)
emit(data)
}
fun saveData(data: List<MyData>) =
liveData(Dispatchers.Default) {
val result = repository.saveDataToDatabase(data)
emit(result)
}
fun data() =
liveData(Dispatchers.IO) {
val data = repository.getDataFromDatabase()
emit(data)
}
}
DataRepository.kt
class DataRepository(application: Application) {
// I won't add how the Retrofit client is created, it's standard
private var client = "MyUrlToGetDataFrom"
private var myDao: MyDao
init {
val myDatabase = MyDatabase.getDatabase(application)
myDao = myDatabase!!.myDao()
}
suspend fun getDataFromServer(since: Long): List<MyData> {
try {
return client.getData(since)
} catch (e: Exception) {
}
}
fun getDataFromDatabase(): List<MyData> = myDao.getAll()
suspend fun insertData(data: List<MyData>) =
myDao.insertData(data)
}
MyDao.kt
#Dao
interface PostsDao {
#Query("SELECT * FROM " + Post.TABLE_NAME + " ORDER BY " + Post.COLUMN_ID + " desc")
suspend fun getAllData(): List<MyData>
#Insert
suspend fun insertData(data: List<MyData>)
}
ListActivity.kt
private lateinit var mDataViewModel: DataViewModel
override fun onCreate(savedInstanceBundle: Bundle?) {
super.onCreate(savedInstanceBundle)
mDataViewModel = ViewModelProvider(this, DataViewModelFactory(contentResolver)).get(DataViewModel::class.java)
getData()
}
private fun getData() {
mDataViewModel.data(getSince()).observe(this, Observer {
saveData(it)
})
}
private fun saveData(data: List<MyData>) {
mDataViewModel.saveData(data)
mDataViewModel.data().observe(this, Observer {
setupRecyclerView(it)
})
}
ListActivity.kt, and possibly the ViewModel and Repository classes where it uses coroutines, are where I'm stuck. getData() retrieves the data from the server without a problem, but when it comes to saving it in the database, then taking that saved data from the database and displaying it to the user I'm unsure of the approach. As I mentioned I'm using Room, but Room will not let you access the database on the main thread.
Remember, I have to save in the database first, then retrieve from the database, so I don't want to call mDataViewModel.data().observe until after it saves to the database.
What is the proper approach to this? I've tried doing CoroutineScope on the mDataViewModel.saveData() then .invokeOnCompletion to do mDataViewModel.data().observe, but it doesn't save to the database. I'm guessing I'm doing my Coroutines incorrectly, but not sure where exactly.
It will also eventually need to delete and update records from the database.
Updated Answer
After reading comments and updated question I figured out that you want to fetch a small list of data and store it to database and show all the data stored in the database. If this is what you want, you can perform the following (omitted DataSouce for brevity) -
In PostDao You can return a LiveData<List<MyData>> instead of List<MyData> and observe that LiveData in the Activity to update the RecyclerView. Just make sure you remove the suspend keyword as room will take care of threading when it returns LiveData.
#Dao
interface PostsDao {
#Query("SELECT * FROM " + Post.TABLE_NAME + " ORDER BY " + Post.COLUMN_ID + " desc")
fun getAllData(): LiveData<List<MyData>>
#Insert
suspend fun insertData(data: List<MyData>)
}
In Repository make 2 functions one for fetching remote data and storing it to the database and the other just returns the LiveData returned by the room. You don't need to make a request to room when you insert the remote data, room will automatically update you as you are observing a LiveData from room.
class DataRepository(private val dao: PostsDao, private val dto: PostDto) {
fun getDataFromDatabase() = dao.getAllData()
suspend fun getDataFromServer(since: Long) = withContext(Dispatchers.IO) {
val data = dto.getRemoteData(since)
saveDataToDatabase(data)
}
private suspend fun saveDataToDatabase(data: List<MyData>) = dao.insertData(data)
}
Your ViewModel should look like,
class DataViewModel(private val repository : DataRepository) : ViewModel() {
val dataList = repository.getDataFromDatabase()
fun data(since: Long) = viewModelScope.launch {
repository.getDataFromServer(since)
}
}
In the Activity make sure you use ListAdapter
private lateinit var mDataViewModel: DataViewModel
private lateinit var mAdapter: ListAdapter
override fun onCreate(savedInstanceBundle: Bundle?) {
...
mDataViewModel.data(getSince())
mDataViewModel.dataList.observe(this, Observer(adapter::submitList))
}
Initial Answer
First of all, I would recommend you to look into Android Architecture Blueprints v2. According to Android Architecture Blueprints v2 following improvements can be made,
DataRepository should be injected rather than instantiating internally according to the Dependency Inversion principle.
You should decouple the functions in the ViewModel. Instead of returning the LiveData, the data() function can update an encapsulated LiveData. For example,
class DataViewModel(private val repository = DataRepository) : ViewModel() {
private val _dataList = MutableLiveData<List<MyData>>()
val dataList : LiveData<List<MyData>> = _dataList
fun data(since: Long) = viewModelScope.launch {
val list = repository.getData(since)
_dataList.value = list
}
...
}
Repository should be responsible for fetching data from remote data source and save it to local data source. You should have two data source i.e. RemoteDataSource and LocalDataSource that should be injected in the Repository. You can also have an abstract DataSource. Let's see how can you improve your repository,
interface DataSource {
suspend fun getData(since: Long) : List<MyData>
suspend fun saveData(list List<MyData>)
suspend fun delete()
}
class RemoteDataSource(dto: PostsDto) : DataSource { ... }
class LocalDataSource(dao: PostsDao) : DataSource { ... }
class DataRepository(private val remoteSource: DataSource, private val localSource: DataSource) {
suspend fun getData(since: Long) : List<MyData> = withContext(Dispatchers.IO) {
val data = remoteSource.getData(since)
localSource.delete()
localSource.save(data)
return#withContext localSource.getData(since)
}
...
}
In your Activity, you just need to observe the dataList: LiveData and submit it's value to ListAdapter.
private lateinit var mDataViewModel: DataViewModel
private lateinit var mAdapter: ListAdapter
override fun onCreate(savedInstanceBundle: Bundle?) {
...
mDataViewModel.data(since)
mDataViewModel.dataList.observe(this, Observer(adapter::submitList))
}