Catch exceptions in the flow.asResult method

Change-Id: I0289e535b8811be95b58b2ea4abe515ab4191cfc
pull/2/head
Adetunji Dahunsi 3 years ago committed by Don Turner
parent 9ffa4d0a20
commit 59c5979c0a

@ -24,4 +24,6 @@ dependencies {
implementation(libs.kotlinx.coroutines.android)
implementation(libs.hilt.android)
kapt(libs.hilt.compiler)
testImplementation(project(":core-testing"))
}

@ -17,6 +17,7 @@
package com.google.samples.apps.nowinandroid.core.result
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
@ -32,4 +33,5 @@ fun <T> Flow<T>.asResult(): Flow<Result<T>> {
Result.Success(it)
}
.onStart { emit(Result.Loading) }
.catch { emit(Result.Error(it)) }
}

@ -0,0 +1,52 @@
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.result
import app.cash.turbine.test
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
class ResultKtTest {
@Test
fun Result_catches_errors() = runTest {
flow {
emit(1)
throw Exception("Test Done")
}
.asResult()
.test {
assertEquals(Result.Loading, awaitItem())
assertEquals(Result.Success(1), awaitItem())
when (val errorResult = awaitItem()) {
is Result.Error -> assertEquals(
"Test Done",
errorResult.exception?.message
)
Result.Loading,
is Result.Success -> throw IllegalStateException(
"The flow should have emitted an Error Result"
)
}
awaitComplete()
}
}
}
Loading…
Cancel
Save