Ricardo C.
09/15/2020, 9:50 AMJoffrey
09/15/2020, 9:57 AMDeferred<YourObject>
.
• All suspend functions could call deferred.await()
, which suspends until the object is ready.
• To set the value during initialization, you can use this.deferred = CompletableDeferred<YourObject>()
and in the initialization callback, use this.deferred.complete(yourObject)
.
Not sure it’s the most elegant option, but I think this solves your problem (if I understood correctly)suspendCoroutine
and resumes when the initialization callback is called. Its return value would be the object passed to the callback by the library. This way you suspend only once, and then you can create a class from it that exposes normal methods using your object.
I guess this is a simpler approach, but I understand that you might have considered it already and were not looking for this.Ricardo C.
09/15/2020, 10:14 AMJoffrey
09/15/2020, 10:16 AMRicardo C.
09/15/2020, 10:20 AMJoffrey
09/15/2020, 10:23 AM// LIBRARY CODE
class LibInitResult
abstract class LibClass {
fun initialize() {
val initResult = LibInitResult()
onInitialized(initResult)
}
abstract fun onInitialized(result: LibInitResult)
}
// WRAPPER
class WrapperClass(private val libInitResult: LibInitResult) {
// expose non-suspending functions using the libInitResult
}
suspend fun buildInitializedWrapper(): WrapperClass =
suspendCoroutine { cont ->
val initializer = object : LibClass() {
override fun onInitialized(result: LibInitResult) {
cont.resume(WrapperClass(result))
}
}
initializer.initialize()
}
buildInitializedWrapper
, you could also use a suspending static factory method (in the companion object of the wrapper class). This would allow a better syntax WrapperClass.create()
or WrapperClass.initialize()
, whatever makes more sense in your actual domain.Ricardo C.
09/15/2020, 10:32 AMJoffrey
09/15/2020, 10:42 AMRicardo C.
09/15/2020, 10:47 AM