generated from icerockdev/moko-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Step 7 - Add client interfaces and callback wrapper
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
...ry/domain/src/commonMain/kotlin/org/example/library/domain/repository/HelloWorldClient.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
|
||
/* | ||
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
package org.example.library.domain.repository | ||
|
||
import io.grpc.examples.helloworld.HelloReply | ||
import io.grpc.examples.helloworld.HelloRequest | ||
import kotlin.coroutines.suspendCoroutine | ||
|
||
interface HelloWorldSuspendClient { | ||
suspend fun sendHello(message: HelloRequest): HelloReply | ||
} | ||
|
||
interface HelloWorldCallbackClient { | ||
fun sendHello(message: HelloRequest, callback: (HelloReply?, Exception?) -> Unit) | ||
} | ||
|
||
class HelloWorldSuspendClientImpl( | ||
private val callbackClientCalls: HelloWorldCallbackClient | ||
): HelloWorldSuspendClient { | ||
|
||
private suspend fun <In, Out> convertCallbackCallToSuspend( | ||
input: In, | ||
callbackClosure: ((In, ((Out?, Throwable?) -> Unit)) -> Unit), | ||
): Out { | ||
return suspendCoroutine { continuation -> | ||
callbackClosure(input) { result, error -> | ||
Unit | ||
when { | ||
error != null -> { | ||
continuation.resumeWith(Result.failure(error)) | ||
} | ||
result != null -> { | ||
continuation.resumeWith(Result.success(result)) | ||
} | ||
else -> { | ||
continuation.resumeWith(Result.failure(IllegalStateException("Incorrect grpc call processing"))) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
override suspend fun sendHello(message: HelloRequest): HelloReply { | ||
return convertCallbackCallToSuspend(message, callbackClosure = { input, callback -> | ||
callbackClientCalls.sendHello(input, callback) | ||
}) | ||
} | ||
} |