Skip to content

Instantly share code, notes, and snippets.

View TorkelV's full-sized avatar

Torkel Velure TorkelV

View GitHub Profile
<Button
android:onClick="@{() -> viewModel.addPhrase(viewModel.phrase, viewModel.translation, viewModel.groupId)}" />
val phraseModule = module {
viewModel { PhraseViewModel(get()) }
single<PhraseDatabase> {
Room.databaseBuilder(
get(),
PhraseDatabase::class.java, "database-name"
).build()
}
single { PreferenceService(get()) }
fun provideDao(db: PhraseDatabase): PhraseDao = db.phraseDao()
@Database(entities = [Phrase::class, Group::class])
abstract class PhraseDatabase : RoomDatabase() {
abstract fun phraseDao(): PhraseDao
}
@Dao
interface PhraseDao {
@Query("SELECT * FROM phrases WHERE `group` = :groupId")
fun getAll(groupId: String): Flow<List<Phrase>>
val activeGroup = prefs.activeGroup.asLiveData(viewModelScope.coroutineContext)
val phrases: LiveData<List<Phrase>> = activeGroup.switchMap { group ->
db.getAll(group)
.asLiveData(viewModelScope.coroutineContext)
}
val canAddNewPhrase: LiveData<Boolean> = Lives.combineLatest(phrase, translation){
phrase, translation -> phrase.isNotEmpty() && translation.isNotEmpty()
}
<Button
android:onClick="@{() -> viewModel.addWord(viewModel.phrase, viewModel.translation, viewModel.groupId)}"
fun addPhrase(phrase: String, translation: String, groupId: String){
if(phrase.isNotEmpty() && translation.isNotEmpty()){
viewmodelScope.launch(Dispatchers.IO){
db.addAll(Phrase(newPhrase, newTranslation))
}
}
}