How can i create an object on worker thread and th...
# kotlin-native
b
How can i create an object on worker thread and then reference it again on another worker execution? Trying to implement redux pattern on background worker...
k
You either need to pass it to that worker from the first, or you need to add it to some kind of global state. You will obviously need to freeze it in the latter case (you should probably only be passing immutable data-state anyway). Any reason you’re working with
Worker
directly? Seems pretty low level
Also, may want to see this https://www.reduxkotlin.org/
b
ReduxKotlin on its own does not work for me, unfortunately. Worker is also not a must, just trying a way to setup communication between UI thread and redux/state thread
k
State is in it’s own thread? I’d just freeze and pass the state. We’re doing something similar in Stately for a new version. Using coroutines currently: https://github.com/touchlab/Stately/blob/kpg/iso_state/stately-isolate/src/commonMain/kotlin/co/touchlab/stately/isolate/IsoState.kt#L12
b
But how do I register callbacks, then? State is already immutable, so not a problem, however when registering callbacks, the captured action freezes the object that's registering it 😕
k
If you’re using a main thread/background thread situation, you can register in the main thread, generate a StableRef to the callback, then hold onto the StableRef. Make sure you go to the main thread when processing callbacks, then once in the main thread, unwrap the StableRef
Might be able to do this with Flow, if OK with coroutines as a dependency. In any case, you can isolate the callback lambda to the main thread and still give a pointer reference to it to a different thread. It’s not beginner level stuff, but it’s not too bad in practice
b
Any way to ensure my coroutine job is run on main thread/worker? Even though it was launched on separate dispatcher
Also, when's the E3 of Stranger Threads? As I think that'll answer my final questions :)