07-20-2023, 09:36 AM
Just wondering others opinion I have 2 ways I can go about doing something and was curious which is better (and hopefully why you think so)
I have 2 files WordRepository and WordViewModel. I can either do the coroutines in the Repo or in the ViewModel both ways work, but hoping someone can give me a clue as to why I would do the coroutines in one or the other and vice versa.
Version A.(Where the coroutine is in the Repo)
WordRepo:
class WordRepository(private val wordDao: WordDao): WordRepo {
@WorkerThread
override suspend fun deleteAllLogsOlderThan(XDays: Int): Int = withContext(IO) {
return@withContext wordDao.deleteAll()
}
}
WordViewModel:
class WordViewModel(private val wordRepository: WordRepo) : ViewModel() {
fun deleteAllLogsOlderThanA(XDays:Int): Int = runBlocking {
wordRepository.deleteAllLogsOlderThan(XDays)
}
}
Version B.(Where the coroutine is in the ViewModel)
Word Repo:
class WordRepository(private val wordDao: WordDao): WordRepo {
@WorkerThread
override suspend fun deleteAllLogsOlderThan(XDays: Int): Int = wordDao.deleteAll()
}
WordViewModel:
class WordViewModel(private val wordRepository: WordRepo) : ViewModel() {
fun deleteAllLogsOlderThanA(XDays:Int): Int = runBlocking {
withContext(IO) {
wordRepository.deleteAllLogsOlderThan(XDays)
}
}
}
I have 2 files WordRepository and WordViewModel. I can either do the coroutines in the Repo or in the ViewModel both ways work, but hoping someone can give me a clue as to why I would do the coroutines in one or the other and vice versa.
Version A.(Where the coroutine is in the Repo)
WordRepo:
class WordRepository(private val wordDao: WordDao): WordRepo {
@WorkerThread
override suspend fun deleteAllLogsOlderThan(XDays: Int): Int = withContext(IO) {
return@withContext wordDao.deleteAll()
}
}
WordViewModel:
class WordViewModel(private val wordRepository: WordRepo) : ViewModel() {
fun deleteAllLogsOlderThanA(XDays:Int): Int = runBlocking {
wordRepository.deleteAllLogsOlderThan(XDays)
}
}
Version B.(Where the coroutine is in the ViewModel)
Word Repo:
class WordRepository(private val wordDao: WordDao): WordRepo {
@WorkerThread
override suspend fun deleteAllLogsOlderThan(XDays: Int): Int = wordDao.deleteAll()
}
WordViewModel:
class WordViewModel(private val wordRepository: WordRepo) : ViewModel() {
fun deleteAllLogsOlderThanA(XDays:Int): Int = runBlocking {
withContext(IO) {
wordRepository.deleteAllLogsOlderThan(XDays)
}
}
}