if i'm using a JNI/native library, and the jvm cra...
# coroutines
c
if i'm using a JNI/native library, and the jvm crashes (
SIGSEGV (0xb)
,
C  [libsystem_pthread.dylib+0x15ad]  pthread_mutex_lock+0x0
) when the value is created outside of a
callbackFlow
but not when it's inside, what would that mean? in other words,
Copy code
val thing = createNativeThing()
callbackFlow {
  thing.onCallback = {
    offer(it)
  }
  thing.start()
}
crashes but
Copy code
callbackFlow {
  val thing = createNativeThing()
  thing.onCallback = {
    offer(it)
  }
  thing.start()
}
does not
🤔 1
my current guess is something to do with threading, but the library claims to be thread safe
g
yeahhh so the question is does the
callbackFlow
factory move threads, and I think the answer to that is yes. So probably what your seeing is
createNativeThing()
being on thread A and
setOnCallback
being on thread B, which might be giving it some trouble
c
hmm, thanks, that makes sense. is there any way around this, particularly if I need
thing
to exist outside of the flow?
g
You might try
Dispatchers.Unconfined
, im still new to flows som not sure how you'd tell callback flow thats what you want
maybe
callbackFlow{ ... }.flowOn(Dispatchers.Unconfined)
i dont think thats a great solution though,
A better solution might be to create your own thread and use thread isolation for your native library
Copy code
val myThread = ExecutorService().asDispatcher()

val thing = withContext(myThread) { createNativeThing() }

callbackFlow { 
  withContext(myThread){
    thing.onCallback = { offer(it) }
    thing.start()
  }
}.flowOn(myThread)
the
flowOn
might not be necessary
the idea is to try to keep all of your interactions with native code in the therad
myThread
c
interesting -- thank you! i'll try that
that worked! (and without the
flowOn
, for future reference)
t
It seems that you omitted to call
awaitClose
at the end of the
callbackFlow
block. Is it on purpose ?
c
i left it out in the example, but even in the real code it was just
awaitClose {}
-- would that be related?