Hey, what are the best practices to initialize a class
private
property with a suspending function return value (suspending supplier, pretty common when dealing with network)? Should I use
lateinit var
? Nullable
var
? Is something like
suspend init { }
planned at some point?
a
Adam Powell
09/24/2019, 4:40 PM
You can use a suspend factory function to construct the object and perform the suspending work before the actual construction. That way the class doesn't have to work with lateinit or nullable state and deal with being partially initialized, and code that accepts an instance of that class doesn't have to worry about it not being ready yet.
s
sdeleuze
09/25/2019, 7:16 AM
Thanks for the idea but I don't think that's doable for my use case (contructor based instantiation by Spring)
sdeleuze
09/25/2019, 8:18 AM
I ended up doing that:
sdeleuze
09/25/2019, 8:18 AM
Copy code
// Connect asynchronously and use `requester()` to get the requester
class MyService {
private var requester: RSocketRequester? = null
private suspend fun requester() = requester ?:
RSocketRequester.builder().connectTcp("localhost", 7000).also { requester = it }
suspend fun doSomething() = requester().route(...)
}
// Or block
class MyService {
private val requester: RSocketRequester = runBlocking {
RSocketRequester.builder().connectTcp("localhost", 7000)
}
suspend fun doSomething() = requester.route(...)
}