Reputation: 857
I have this query in my DAO
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertFolders(folderList: List<Folder>)
@Query("select * from attachments_folders where companyId = :companyId")
fun getFoldersByCompanyId(companyId: Int): LiveData<List<Folder>>
I have this ViewModel
class FolderViewModel :ViewModel(){
private val folders: MutableLiveData<List<Folder>> by lazy {
MutableLiveData<List<Folder>>().also {
loadFolders()
}
}
fun getFolders(): LiveData<List<Folder>> {
return folders
}
private fun loadFolders() {
FolderDao().getFoldersByCompanyId(Prefs.getInt(PreferenceKeys.COMPANY_ID, 0))
}
}
and then this in my activity
FolderViewModel model = ViewModelProviders.of(this).get(FolderViewModel.class);
model.getFolders().observe(this, new Observer<List<Folder>>() {
@Override public void onChanged(@Nullable List<Folder> folders) {
if(folders != null) {
if (folders.size() != 0) {
Fragment companyFragment = AttachmentsListFragmentFactory.newFolderAttachmentsFragment(new ArrayList<>(folders), getJobId());
ft.replace(android.R.id.content, companyFragment);
currentFragment = companyFragment;
} else {
Fragment companyFragment = AttachmentsListFragmentFactory.newCompanyAttachmentsFragment(false, getJobId());
ft.replace(android.R.id.content, companyFragment);
currentFragment = companyFragment;
}
}
}
});
It keeps hitting the else block. There are 3 folders in the database. so i dont get why its doing that and if there is a way to rectify this because if there are folders in the db it should use the if fragment not the else one.
inserting folders
FolderDao().insertFolders(
Gson().fromJson<List<Folder>>(JsonHelper.getArraylistFromJson(response.body()?.string(), "folderList"),
object : TypeToken<List<Folder>>() {}.type))
EDIT: It seems that folders always seems to be null
Upvotes: 0
Views: 54
Reputation: 18487
The issue is here with the usage of also
.
private val folders: MutableLiveData<List<Folder>> by lazy {
MutableLiveData<List<Folder>>().also {
loadFolders()
}
}
Definition of also
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
As you can see, loadFolders()
in also would not change anything. So you are not setting anything to the live data.
You should directly return
fun getFolders(): LiveData<List<Folder>> {
return loadFolders()
}
Using lazy
is probably not a right choice since you may want to change the folder id.
Upvotes: 1