Я пытаюсь запустить два запуска сопрограммы подряд. Как я могу это заархивировать?
первый пытается получить продолжительность. Когда это будет успешно, сбор должен остановиться и запуститься второй запуск моей сопрограммы.
Я не знаю, правильный ли это путь. Но мне нужно сначала получить продолжительность, а затем обработать вторую часть.
Каждая часть работает сама по себе. но не вместе, потому что сбор блокирует. Еще пробовал сделать return@collect, но не получается
@Singleton
class AddDayReminderNotification(
private val notificationUseCases: NotificationUseCases,
private val dayUseCases: DayUseCases,
private val weekUseCases: WeekUseCases,
private val settingsUseCases: SettingsUseCases
) {
suspend fun addNotification(context: Context?, notification: Notification) {
var neededDuration: Duration = Duration.ZERO
val dayOfWeekIndex = getDayOfWeekLocalized(notification.date)
coroutineScope {
val dayDuration = launch {
weekUseCases.getAllWeeks()
.collect { weekResponse ->
when (weekResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
val week =
weekResponse.data?.firstOrNull {
it.week == getWeekOfYearByLocalDate(
notification.date
) && it.year == notification.date.year
}
if (week != null) {
val stringValue = week.weekDailyDurations
val splitString = stringValue.split(":")
val intList: MutableList = mutableListOf()
if (splitString.count() == 7) {
splitString.forEach {
try {
intList.add(it.toInt())
} catch (e: NumberFormatException) {
println("Error: $it is not a valid integer")
coroutineContext.cancel()
}
}
}
neededDuration = intList[dayOfWeekIndex].minutes
} else {
settingsUseCases.getSetting(SettingsIndex.WeekDailyDurations.getIndex())
.collect { response ->
when (response) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
val stringValue = response.data?.stringValue
if (stringValue.isNullOrEmpty()) {
coroutineContext.cancel()
} else {
val splitString = stringValue.split(":")
val intList: MutableList =
mutableListOf()
if (splitString.count() == 7) {
splitString.forEach {
try {
intList.add(it.toInt())
} catch (e: NumberFormatException) {
println("Error: $it is not a valid integer")
coroutineContext.cancel()
}
}
}
neededDuration = intList[dayOfWeekIndex].minutes
}
}
}
}
}
}
}
}
}
val notificationCreator = launch {
if (neededDuration != Duration.ZERO) {
dayUseCases.getAllDays()
.collect { dayResponse ->
when (dayResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
if (dayResponse.data != null) {
val foundDay =
dayResponse.data.firstOrNull { it.date == notification.date && it.isActive }
if (foundDay == null) {
notificationUseCases.getAllNotifications()
.collect { notificationResponse ->
when (notificationResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
if (notificationResponse.data != null) {
val dayReminderNotification =
notificationResponse.data.firstOrNull { it.date == notification.date && it.notificationType == NotificationType.DayUnchangedReminder.value }
if (dayReminderNotification == null) {
notificationUseCases.upsertNotification(
notification
)
context?.let {
DayReminderNotificationService(
it
)
}
?.showNotification(
notification.title + neededDuration.toFloatHours(),
notification.description,
notification.notificationType
)
}
coroutineContext.cancel()
}
}
}
}
}
coroutineContext.cancel()
}
}
}
}
} else {
coroutineContext.cancel()
}
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... nes-in-row
Android Kotlin запускает две сопрограммы подряд ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1734369992
Anonymous
Я пытаюсь запустить два запуска сопрограммы подряд. Как я могу это заархивировать?
первый пытается получить продолжительность. Когда это будет успешно, сбор должен остановиться и запуститься второй запуск моей сопрограммы.
Я не знаю, правильный ли это путь. Но мне нужно сначала получить продолжительность, а затем обработать вторую часть.
Каждая часть работает сама по себе. но не вместе, потому что сбор блокирует. Еще пробовал сделать return@collect, но не получается
@Singleton
class AddDayReminderNotification(
private val notificationUseCases: NotificationUseCases,
private val dayUseCases: DayUseCases,
private val weekUseCases: WeekUseCases,
private val settingsUseCases: SettingsUseCases
) {
suspend fun addNotification(context: Context?, notification: Notification) {
var neededDuration: Duration = Duration.ZERO
val dayOfWeekIndex = getDayOfWeekLocalized(notification.date)
coroutineScope {
val dayDuration = launch {
weekUseCases.getAllWeeks()
.collect { weekResponse ->
when (weekResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
val week =
weekResponse.data?.firstOrNull {
it.week == getWeekOfYearByLocalDate(
notification.date
) && it.year == notification.date.year
}
if (week != null) {
val stringValue = week.weekDailyDurations
val splitString = stringValue.split(":")
val intList: MutableList = mutableListOf()
if (splitString.count() == 7) {
splitString.forEach {
try {
intList.add(it.toInt())
} catch (e: NumberFormatException) {
println("Error: $it is not a valid integer")
coroutineContext.cancel()
}
}
}
neededDuration = intList[dayOfWeekIndex].minutes
} else {
settingsUseCases.getSetting(SettingsIndex.WeekDailyDurations.getIndex())
.collect { response ->
when (response) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
val stringValue = response.data?.stringValue
if (stringValue.isNullOrEmpty()) {
coroutineContext.cancel()
} else {
val splitString = stringValue.split(":")
val intList: MutableList =
mutableListOf()
if (splitString.count() == 7) {
splitString.forEach {
try {
intList.add(it.toInt())
} catch (e: NumberFormatException) {
println("Error: $it is not a valid integer")
coroutineContext.cancel()
}
}
}
neededDuration = intList[dayOfWeekIndex].minutes
}
}
}
}
}
}
}
}
}
val notificationCreator = launch {
if (neededDuration != Duration.ZERO) {
dayUseCases.getAllDays()
.collect { dayResponse ->
when (dayResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
if (dayResponse.data != null) {
val foundDay =
dayResponse.data.firstOrNull { it.date == notification.date && it.isActive }
if (foundDay == null) {
notificationUseCases.getAllNotifications()
.collect { notificationResponse ->
when (notificationResponse) {
is Response.Failure -> {
coroutineContext.cancel()
}
is Response.Loading -> {}
is Response.Success -> {
if (notificationResponse.data != null) {
val dayReminderNotification =
notificationResponse.data.firstOrNull { it.date == notification.date && it.notificationType == NotificationType.DayUnchangedReminder.value }
if (dayReminderNotification == null) {
notificationUseCases.upsertNotification(
notification
)
context?.let {
DayReminderNotificationService(
it
)
}
?.showNotification(
notification.title + neededDuration.toFloatHours(),
notification.description,
notification.notificationType
)
}
coroutineContext.cancel()
}
}
}
}
}
coroutineContext.cancel()
}
}
}
}
} else {
coroutineContext.cancel()
}
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79285544/android-kotlin-run-two-coroutines-in-row[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия