Hey, what are the best practices to initialize a c...
# coroutines
s
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
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
Thanks for the idea but I don't think that's doable for my use case (contructor based instantiation by Spring)
I ended up doing that:
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(...)
    }
d
You can use
Deferred
or
CompletableDeferred
It will be thread safe