<@U3SK5B492> I want to write a class that doesn’t ...
# kotlin-native
s
@olonho I want to write a class that doesn’t have to worry about threading concerns at all. It only is ever used by one thread. Then I want to create a wrapper for that class (eventually I want to generate it with a compiler plugin, but for now I’m manually writing it), that exposes the same API, but via suspend functions, and is asynchronous, that delegates to the original class, mostly via
withContext
calls. This means that the wrapper will need to be frozen, and the core class that the wrapper delegates too will need to not be frozen. The wrapper has to have a reference to the core class though. How can I accomplish this? Someone mentioned using a
StableRef
, which seems like it will do the job, but then it has to be disposed in order to not cause a memory leak for a reference. That means that a
dispose
function has to be added to my wrapper. I’d like to not pollute my interface and require an API like that. Is there another way?
Copy code
internal class ExampleWrapper {
    private val delegate = StableRef.create(Example())
    
    suspend fun doSomething(): String = withContext(Platform.dispatcher) {
        delegate.get().doSomething()
    }
    
    fun dispose() {
        delegate.dispose()
    }
}

private class Example {
    fun doSomething(): String {
        // Do something interesting
        return "Blah"
    }
}
o
instead of referring the class, you can have a
Worker
which manages
Example
instances and perform operations via queue. Instance can be referred by an integer handle or map to identify the instance you’re working with, and periodically clean unused instances by storing weak reference to the
Wrapper
and removing element if weak ref is zeroed out
k
i'd like to know the proper way to have a
Worker
manage an
Example
considering there can't be any references to the
Example
outside of the
Worker
s
@olonho
Worker
frustratingly only allows one event to be processed at a time though. I’m making network requests which could take seconds. There is no reason for that class instance to be inaccessible for potentially seconds. That’s VERY limiting. Is there a way to remove the queuing restriction from
Worker
, or is there another way?
@olonho This seems pretty simple. I’m surprised I can’t do this easily.
k
if I had a dollar for every time I said that when working with K/N concurrency, I wouldn't need to work anymore
f
I replaced a
StableRef
in my project with
Channels
.