https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

conner

07/08/2020, 9:36 PM
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

groostav

07/08/2020, 9:40 PM
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

conner

07/08/2020, 9:42 PM
hmm, thanks, that makes sense. is there any way around this, particularly if I need
thing
to exist outside of the flow?
g

groostav

07/08/2020, 9:43 PM
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

conner

07/08/2020, 9:57 PM
interesting -- thank you! i'll try that
that worked! (and without the
flowOn
, for future reference)
t

tseisel

07/09/2020, 7:38 AM
It seems that you omitted to call
awaitClose
at the end of the
callbackFlow
block. Is it on purpose ?
c

conner

07/09/2020, 1:11 PM
i left it out in the example, but even in the real code it was just
awaitClose {}
-- would that be related?
6 Views