From eb616eedc707d78c0895bcd19bae6301abe200f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Pich?= Date: Tue, 1 Sep 2020 09:31:01 +0200 Subject: [PATCH] Fix crash in flowWithResourceIn() (#933) --- .../modules/timetable/TimetablePresenter.kt | 1 + .../io/github/wulkanowy/utils/FlowUtils.kt | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt index e410eeb9..8581b73c 100644 --- a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach import timber.log.Timber +import java.lang.NullPointerException import java.time.LocalDate import java.time.LocalDate.now import java.time.LocalDate.of diff --git a/app/src/main/java/io/github/wulkanowy/utils/FlowUtils.kt b/app/src/main/java/io/github/wulkanowy/utils/FlowUtils.kt index 736a4270..31499405 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/FlowUtils.kt +++ b/app/src/main/java/io/github/wulkanowy/utils/FlowUtils.kt @@ -3,6 +3,7 @@ package io.github.wulkanowy.utils import io.github.wulkanowy.data.Resource import io.github.wulkanowy.data.Status import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter @@ -69,22 +70,24 @@ inline fun networkBoundResource( fun flowWithResource(block: suspend () -> T) = flow { emit(Resource.loading()) - try { - emit(Resource.success(block())) + emit(try { + Resource.success(block()) } catch (e: Throwable) { - emit(Resource.error(e)) - } + Resource.error(e) + }) } fun flowWithResourceIn(block: suspend () -> Flow>) = flow { emit(Resource.loading()) try { - block().collect { - if (it.status != Status.LOADING) { // LOADING is already emitted - emit(it) + block() + .catch { emit(Resource.error(it)) } + .collect { + if (it.status != Status.LOADING) { // LOADING is already emitted + emit(it) + } } - } } catch (e: Throwable) { emit(Resource.error(e)) }