Skip to content

Commit

Permalink
fix(api): Fix the handling of exceptions when subscribing with Kotlin…
Browse files Browse the repository at this point in the history
… Facade (#2821)
  • Loading branch information
mattcreaser authored May 16, 2024
1 parent 9f900a0 commit 300c6d9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions core-kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dependencies {
testImplementation(libs.test.mockk)
testImplementation(libs.test.kotlin.coroutines)
testImplementation(project(":testmodels"))
testImplementation(libs.test.kotest.assertions)
}

android.kotlinOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ class KotlinApiFacade(private val delegate: Delegate = Amplify.API) : Api {
{ subscription.completions.tryEmit(Unit) }
)
}
subscription.cancelable = operation as Cancelable
// If subscribe fails it does not return an operation, and instead invokes the onSubscriptionFailure callback
operation?.let { subscription.cancelable = operation }
return subscription.awaitStart()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import com.amplifyframework.api.graphql.GraphQLResponse
import com.amplifyframework.api.rest.RestOptions
import com.amplifyframework.api.rest.RestResponse
import com.amplifyframework.core.Consumer
import io.kotest.assertions.throwables.shouldThrow
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
Expand All @@ -32,6 +33,7 @@ import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test

Expand Down Expand Up @@ -174,6 +176,25 @@ class KotlinApiFacadeTest {
api.subscribe(request).first()
}

@Test
fun `subscribe throws when exception occurs during subscription establishment`() = runTest {
val request = mockk<GraphQLRequest<String>>()
val expectedFailure = ApiException("uh", "oh")

every {
delegate.subscribe(eq(request), any(), any(), any(), any())
} answers {
val indexOfErrorConsumer = 3
val onError = it.invocation.args[indexOfErrorConsumer] as Consumer<ApiException>
GlobalScope.launch(Dispatchers.IO) { onError.accept(expectedFailure) }
null
}

shouldThrow<ApiException> {
api.subscribe(request).first()
}
}

/**
* When the underlying get() emits a response,
* it should be returned from the coroutine API.
Expand Down

0 comments on commit 300c6d9

Please sign in to comment.