Я пытаюсь выполнить эти шаги в указанном порядке.
- Заполнить мою базу данных Room данными.
- Обновить переменную списка (в ViewModel) текущим содержимым базы данных.
- Переменная списка доступа (в ViewModel) из моего фрагмента.
После выполнения я получаю тосты в этом порядке
- 0 в MythFragment
- 5 в MythViewModel
Я ожидал того же количества элементов. Это отличается из-за сопрограмм? Обязательно ли использовать LiveData?
MythFragment.kt
class MythFragment : Fragment() {
private lateinit var viewModel: MythViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_myth, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MythViewModel::class.java)
viewModel.populateMyths()
viewModel.fetchFromDatabase()
Toast.makeText(activity, "${viewModel.myths.size} in MythFragment", Toast.LENGTH_SHORT)
.show()
}
}
MythViewModel.kt
class MythViewModel(application: Application) : BaseViewModel(application) {
var myths = listOf<Myth>()
fun populateMyths() {
launch {
val dao = MythDatabase(getApplication()).mythDao()
if (dao.getRowCount() > 0)
return@launch
val mythList = listOf<Myth>(
Myth("This is the myth 1", "This is the evaluation of the myth 1"),
Myth("This is the myth 2", "This is the evaluation of the myth 2"),
Myth("This is the myth 3", "This is the evaluation of the myth 3"),
Myth("This is the myth 4", "This is the evaluation of the myth 4"),
Myth("This is the myth 5", "This is the evaluation of the myth 5")
)
dao.insertAll(
*mythList.toTypedArray()
)
}
}
fun fetchFromDatabase() {
launch {
myths = MythDatabase(getApplication()).mythDao().getAllMyths()
Toast.makeText(getApplication(), "${myths.size} in MythViewModel", Toast.LENGTH_SHORT)
.show()
}
}
}
BaseViewModel.kt
abstract class BaseViewModel(application: Application) : AndroidViewModel(application),
CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCleared() {
super.onCleared()
job.cancel()
}
}