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

Ivan

02/23/2021, 7:17 AM
Hi folks. I need to retrive information from coroutine context (ktor logged user) in an implementation of a function from an abstract java class provided by an external library. I can't implement this function as a suspend function and so i can't access to the coroutine context. Do you have any suggestion?
n

Niklas Gürtler

02/23/2021, 7:22 AM
Does your function need to suspend?
i

Ivan

02/23/2021, 7:27 AM
No, it doesn't. I need to implement this java abstract class from my kotlin/ktor project:
Copy code
@FunctionalInterface
public interface CurrentUserProvider {


  Object currentUser();
}
But i can declase currentUser as suspend function, and this function is called from library as an internal callback
n

Niklas Gürtler

02/23/2021, 7:33 AM
Copy code
@FunctionalInterface
class MyCurrentUserProvider (val coroScope : CoroutineScope) : CurrentUserProvider () {
  
  fun currentUser() : java.lang.Object () {
    coroScope.whatever ()
  }
}
i

Ivan

02/23/2021, 7:58 AM
I already try this solution but coroutine context thet can i pass to MyCurrentUserProvider is different from coroutine context that ktor use on http call and not contain the user info. I need to find a way to retrive the correct coroutine context directly from currentUser function.
n

Niklas Gürtler

02/23/2021, 8:06 AM
does ktor call currentUser directly? Or does ktor call something in your app, which then calls something in the Java lib, which then calls currentUser?
i

Ivan

02/23/2021, 8:07 AM
the second one
n

Niklas Gürtler

02/23/2021, 8:08 AM
so then can't your app determine the ktor context _bef_ore you call the external library, pass it to your CurrentUserProvider implementation, and then do the call?
i

Ivan

02/23/2021, 8:12 AM
exactly, i think that the only way is to save user information in currentThread in some way when ktor call start and retrieve it from currentUser
n

Niklas Gürtler

02/23/2021, 8:13 AM
why in currentThread? Why not simply in a member variable of your CurrentUserProvider implementation?
i

Ivan

02/23/2021, 8:14 AM
CurrentUserProvider is a singleton, shared for all call
n

Niklas Gürtler

02/23/2021, 8:15 AM
what about passing a lambda that captures the currentContext variable instead of a CurrentUserProvider implementation?
You need to pass it explicitly to your function as parameter or receiver.
Technically, it would be even possible to expose 
coroutineContext
 as a 
ThreadLocal
.
5 Views