How to get lambda/function signature in Kotlin? - kotlin

I have developed the code below:
import com.google.gson.Gson
import com.rabbitmq.client.Delivery
typealias MessageHandler<T> = (payload: T, args: HashMap<String, String>) -> Unit
class MessageRouter {
private var handlers: HashMap<String, Function<Unit>> = hashMapOf()
fun <T> bind(routingKey: String, handler: MessageHandler<T>) : MessageRouter {
handlers[routingKey] = handler
return this
}
fun consume(message: Delivery) {
if(message.envelope.routingKey in handlers) {
val currentHandler = handlers[message.envelope.routingKey]
if(message.properties.contentType == "application/json") {
///// TODO: Get function signature!
val gson = Gson()
//// TODO: Deserialize data and call the handler function
}
}
}
}
To be used as follows:
val messageRouter = MessageRouter()
val messageRouter = MessageRouter()
messageRouter.bind(EventSubscriberConstants.REGISTRATION_ROUTING_KEY) { user: UserDTO, _ -> register(user) }
basicConsume(
queueName, true,
{ _, message ->
messageRouter.consume(message)
}, null, null
)
I need the input lambda signature to extract UserDTO class and use Gson to deserialize it and process. I can not find any way to get function signature in Kotlin!

Related

RxJava Scheduler.Worker equivalent in Kotlin coroutines

I try to migrate below code which RxJava to Kotlin coroutines.
This uses uses RxJava Scheduler.Worker to do json parsin in own thread. Is there something similar in Kotlin Coroutines?
// RxJava
class MessagesRepository() {
private val messagesSubject = PublishSubject.create<Message>()
val messages = messagesSubject.toFlowable(BackpressureStrategy.BUFFER)
val scheduler = Schedulers.computation()
private fun setClientCallbacks() {
val worker = scheduler.createWorker()
val processMessage = { message: ApiMessage ->
worker.schedule {
val msg = moshiJsonAdapter.fromJson(message.toString())
messagesSubject.onNext(msg)
}
}
client.setCallback(object : Callback {
override fun messageArrived(topic: String, message: ApiMessage) {
processMessage(message)
}
})
}
}
// Coroutines
class MessagesRepository() {
private val _messages = MutableSharedFlow<Message>(
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val messages: SharedFlow<Message> = _messages.asSharedFlow()
private fun setClientCallbacks() {
client.setCallback(object : Callback {
override fun messageArrived(topic: String, message: ApiMessage) {
// How to move this json parsin to own thread
val msg = moshiJsonAdapter.fromJson(message.toString())
_messages.tryEmit(vehicle)
}
})
}
}

ktor-client : how to serialize a post body as a specific type

With ktor client, I've got a non-serializable object derived from a serializable object like so:
#Serializable
#SerialName("login-request")
open class LoginRequest (
open val email : String = "",
open val password : String = ""
) : ServiceRequestPayload
impl class
class LoginRequestVo : LoginRequest("", ""), NodeComponent by NodeComponentImpl() {
override val email: String by subject("")
override val password: String by subject("")
}
Now when I manually use kotlinx serialization on this like so:
val request : LoginRequest = LoginRequestVo().apply {
email = "test#gmail.com"
password = "password"
}
val str = Json.encodeToString(request)
println(str)
It correctly serializes it, and when deserialized on the other side, it correctly deserializes to LoginRequest. However, when I use ktor-client to serialize my object, it complains that LoginRequestVo is not serializable. The example code below uses some other objects from my project and has more information that you need, but the gist is that the type of U in the invoke function and therefore the request.payload expression is type LoginRequest as specified by the LoginServiceImpl below.
suspend inline fun <T, U: ServiceRequestPayload> HttpClient.invoke(desc : EndpointDescriptor<T, U>, request : ServiceRequest<U>? ) : ServiceResponse {
val path = "/api${desc.path}"
return when(desc.method) {
HttpMethod.GET -> {
get(path)
}
HttpMethod.POST -> {
if (request == null) {
post(path)
} else {
post(path) {
contentType(ContentType.Application.Json)
body = request.payload
}
}
}
HttpMethod.DELETE -> delete(desc.path)
HttpMethod.PUT -> {
if (request == null) {
put(path)
} else {
post(path) {
contentType(ContentType.Application.Json)
body = request.payload
}
}
}
}
}
class LoginServiceImpl(
context : ApplicationContext
) : LoginService {
private val client by context.service<HttpClient>()
override suspend fun login(request: ServiceRequest<LoginRequest>) = client.invoke(LoginServiceDesc.login, request)
override suspend fun register(request: ServiceRequest<LoginRequest>) = client.invoke(LoginServiceDesc.register, request)
}
The error I get is:
My question is, Is there a way to specify to ktor-client the type or the serializer to use when it needs to serialize a body?

How to implement volleyresponse listener using Kotlin

I am trying to move my volley requests into a class, so I can use it for multiple network calls. I need a way to access the response listener in whatever activity I use in this class. i saw some examples in java, But I am finding it difficult to do achieve this.
import android.content.Context
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
interface VolleyResponse{
}
class NetworkCall(LINK:String,
CONTEXT:Context,
CACHE:Boolean,
PARAMS: HashMap<String, String> = HashMap(),
SuccessListener: Response.Listener<String>,
ErrorListener: Response.ErrorListener ) {
private var link:String = LINK
private var context: Context = CONTEXT
var cache: Boolean = CACHE
var PARAMS: HashMap<String,String> = HashMap()
fun RunTask( ){
//BUILD the request and listen for error or success
var request = object : StringRequest(
Request.Method.POST,link,
Response.Listener { response -> { }
},
Response.ErrorListener { error -> { }
}) {
override fun getParams(): HashMap<String, String> {
return PARAMS
}
}
var RequestQueue: RequestQueue = Volley.newRequestQueue(context)
request.setShouldCache(cache)
request.setRetryPolicy(DefaultRetryPolicy(10000, 0, 0F))
}
}
and i call it like this...
fun processLogin() {
var params:HashMap<String,String> = HashMap()
params.put("user_email","username")
params.put("user_password","password")
var networkCall = NetworkCall("",applicationContext,false,params)
}
I just need to be able to access the response listeners in my processLogin function.
First you have to define implementations of Response.Listener<String> and Response.ErrorListener in the class where processLogin is defined, this can be done as following
private val successListener = Response.Listener<String> {
// Do something when response is received
}
private val errorListener = Response.ErrorListener {
// Do something when error is received
}
now pass these as parameters when you call processLogin as following
var networkCall = NetworkCall("",applicationContext,false,params, successListener, errorListener)
Finally you need to update your NetworkCall class so that these listeners are called on network action
fun RunTask( ){
//BUILD the request and listen for error or success
var request = object : StringRequest(
Request.Method.POST,link,
SuccessListener, // Pass listeners to request
ErrorListener) {
override fun getParams(): HashMap<String, String> {
return PARAMS
}
}

How i can use Flow on swift Kotlin multiplatform?

I am creating my first kotlin multiplataform project, and i'm having some difficulty to use the kotlin flow on swift. I created the models, server data requests as common file using kotlin flow and ktor, the the view model and ui layers i am creating as native. So, i have no experience with swift development, and beyond that i' having a lot of trouble to use flow on swift view model. Searching for an answer to my problem i found a class described as CommonFlow, which aims to be used as a common code for both languages(kotlin, swift, but i'm having an error that gives me little or no clue as to why it happens or, probably, it's just my lack of dominion with xcode and swift programming:
So this is the code part that xcode points the error:
Obs: sorry about the image i thought that maybe this time it would be more descriptive
And this its all i got from the error
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee5928ff8)
MY Ios ViewModel:
class ProfileViewModel: ObservableObject {
private let repository: ProfileRepository
init(repository: ProfileRepository) {
self.repository = repository
}
#Published var authentication: Authetication = Authetication.unauthenticated(false)
#Published var TokenResponse: ResponseDTO<Token>? = nil
#Published var loading: Bool = false
func authenticate(email: String, password: String) {
DispatchQueue.main.async {
if(self.isValidForm(email: email, password: password)){
self.repository.getTokenCFlow(email: email, password: password).watch{ response in
switch response?.status {
case StatusDTO.success:
self.loading = false
let token: String = response!.data!.accessToken!
SecretStorage().saveToken(token: token)
self.authentication = Authetication.authenticated
break;
case StatusDTO.loading:
self.loading = true
break;
case StatusDTO.error:
print("Ninja request error \(String(describing: response!.error!))}")
break;
default:
break
}
}
}
}
}
private func isValidForm(email: String, password: String) -> Bool {
var invalidFields = [Pair]()
if(!isValidEmail(email)){
invalidFields.append(Pair(first:"email invalido",second: "email invalido"))
}
if(password.isEmpty) {
invalidFields.append(Pair(first:"senha invalida",second: "senha invalida"))
}
if(!invalidFields.isEmpty){
self.authentication = Authetication.invalidAuthentication(invalidFields)
return false
}
return true
}
private func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailPred.evaluate(with: email)
}
}
class Pair {
let first: String
let second: String
init(first:String, second: String) {
self.first = first
self.second = second
}
}
enum Authetication {
case invalidAuthentication([Pair])
case authenticated
case persistentAuthentication
case unauthenticated(Bool)
case authenticationFailed(String)
}
The repository methods:
override fun getToken(email: String, password: String): Flow<ResponseDTO<Token>> = flow {
emit(ResponseDTO.loading<Token>())
try {
val result = api.getToken(GetTokenBody(email, password))
emit(ResponseDTO.success(result))
} catch (e: Exception) {
emit(ResponseDTO.error<Token>(e))
}
}
#InternalCoroutinesApi
override fun getTokenCFlow(email: String, password: String): CFlow<ResponseDTO<Token>> {
return wrapSwift(getToken(email, password))
}
The Class CFLOW:
#InternalCoroutinesApi
class CFlow<T>(private val origin: Flow<T>): Flow<T> by origin {
fun watch(block: (T) -> Unit): Closeable {
val job = Job()
onEach {
block(it)
}.launchIn(CoroutineScope(Dispatchers.Main + job))
return object: Closeable {
override fun close() {
job.cancel()
}
}
}
}
#FlowPreview
#ExperimentalCoroutinesApi
#InternalCoroutinesApi
fun <T> ConflatedBroadcastChannel<T>.wrap(): CFlow<T> = CFlow(asFlow())
#InternalCoroutinesApi
fun <T> Flow<T>.wrap(): CFlow<T> = CFlow(this)
#InternalCoroutinesApi
fun <T> wrapSwift(flow: Flow<T>): CFlow<T> = CFlow(flow)
There is an example of using flows in KampKit
https://github.com/touchlab/KaMPKit
I will paste an excerpt from NativeViewModel (iOS)
class NativeViewModel(
private val onLoading: () -> Unit,
private val onSuccess: (ItemDataSummary) -> Unit,
private val onError: (String) -> Unit,
private val onEmpty: () -> Unit
) : KoinComponent {
private val log: Kermit by inject { parametersOf("BreedModel") }
private val scope = MainScope(Dispatchers.Main, log)
private val breedModel: BreedModel = BreedModel()
private val _breedStateFlow: MutableStateFlow<DataState<ItemDataSummary>> = MutableStateFlow(
DataState.Loading
)
init {
ensureNeverFrozen()
observeBreeds()
}
#OptIn(FlowPreview::class)
fun observeBreeds() {
scope.launch {
log.v { "getBreeds: Collecting Things" }
flowOf(
breedModel.refreshBreedsIfStale(true),
breedModel.getBreedsFromCache()
).flattenMerge().collect { dataState ->
_breedStateFlow.value = dataState
}
}
This ViewModel is consumed in swift like this:
lazy var adapter: NativeViewModel = NativeViewModel(
onLoading: { /* Loading spinner is shown automatically on iOS */
[weak self] in
guard let self = self else { return }
if (!(self.refreshControl.isRefreshing)) {
self.refreshControl.beginRefreshing()
}
},
onSuccess: {
[weak self] summary in self?.viewUpdateSuccess(for: summary)
self?.refreshControl.endRefreshing()
},
onError: { [weak self] error in self?.errorUpdate(for: error)
self?.refreshControl.endRefreshing()
},
onEmpty: { /* Show "No doggos found!" message */
[weak self] in self?.refreshControl.endRefreshing()
}
)
In short, the flow is kept wrapped in kotlin mp land and leveraged in iOS by using traditional callback interfaces.

Not able to call Multiple API Parallely using Retrofit kotlin rxjava and how to call flatMap and zip together with Common Place error handling

What i want to achive is
Call IndexList API and display the responded list in a spinner -> Click on Spinner item i want to call 3 api in parallel using .zip operator and display in DetailViewModel
I am using flatmap for calling api in sequence
In first flatmap i am calling IndexList api and i am passing IndexList response to call 3 multiple api in parallel using Observable.zip operator but i am not able
to achive the second part of calling 3 API in parallel and display in view model
Code Snippet:
Spinner Click :
spinner_index_list?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
//Performing action onItemSelected and onNothing selected
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
mRecyclerView?.visibility = View.GONE
//Select item from spinner calling API
val symbolDefaultGroup = SymbolForDefaultGroup(indexExchangeSegmentList[pos], parent.getItemAtPosition(pos).toString())
grpIndexViewModel.getSearchSymbol(symbolDefaultGroup)?.observe(this#FragmentWatchlist, Observer { instrumentByIdResponse ->
mDataProvider = ExpandableDataProvider(instrumentByIdResponse)
mRecyclerView?.visibility = View.VISIBLE
if (instrumentByIdResponse != null)
initRecyclerView(savedInstanceState)
})
}
ViewModel :
fun getSearchSymbol(symbolForDefaultGroup: SymbolForDefaultGroup): LiveData<List<InstrumentByIdResponse>>? {
instrumentByIdResponse = null
instrumentByIdResponse = MutableLiveData<List<InstrumentByIdResponse>>()
instrumentByIdResponse = groupRepository.getSearchSymbol(symbolForDefaultGroup)
L.d("get symbol for default group method")
return instrumentByIdResponse
}
Repository:
override fun getSearchSymbol(symbolForDefaultGroup: SymbolForDefaultGroup): LiveData<List<InstrumentByIdResponse>> {
val mutableLiveData = MutableLiveData<List<InstrumentByIdResponse>>()
val instrumentsIdList = ArrayList<Instrument>()
val marketDataQuotesList = ArrayList<QuotesList>()
val subscriptionList = ArrayList<SubscriptionList>()
val symbolFroDefaultGroup: Observable<BaseResponse<SymbolForDefaultGroupResponse>> = remoteServices.requestSymbolForDefaultGroup(symbolForDefaultGroup)
symbolFroDefaultGroup
.flatMap { response ->
for (i in 0 until response.result!!.instruments.size) {
instrumentsIdList.add(Instrument(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
marketDataQuotesList.add(QuotesList(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
subscriptionList.add(SubscriptionList(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
}
val instrumentByIdResult = InstrumentById(instrumentsIdList)
val marketDataQuotes = MarketDataQuotes("ABC", "ABC", marketDataQuotesList, 1111)
val subscriptionList = Subscribe("ABC", "ABC", "Mobile", subscriptionList, 1111)
return#flatMap getDetails(instrumentByIdResult, marketDataQuotes, subscriptionList)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : ErrorCallBack<BaseResponse<List<InstrumentByIdResponse>>>() {
override fun onSuccess(t: BaseResponse<List<InstrumentByIdResponse>>) {
L.d("Success of Search Instrument")
mutableLiveData.value = transform1(t)
}
})
return mutableLiveData
}
private fun transform1(response: BaseResponse<List<InstrumentByIdResponse>>?): List<InstrumentByIdResponse>? {
return response!!.result!!.toList()
}
fun getDetails(instrumentById: InstrumentById, marketDataQuotes: MarketDataQuotes, subscription: Subscribe): Observable<DetailsModel> {
return Observable.zip(
remoteServices.requestInstrumentById(instrumentById),
remoteServices.requestMarketDataQuotes(marketDataQuotes),
remoteServices.requestSubscribe(subscription),
/*Observable.fromArray(remoteServices.requestInstrumentById(instrumentById)),
Observable.fromArray(remoteServices.requestMarketDataQuotes(marketDataQuotes)),
Observable.fromArray(remoteServices.requestSubscribe(subscription)),*/
Function3<List<InstrumentByIdResponse>, MarketDataQuotesResponse, SubscribeResult, DetailsModel>
{ instrumentByIdResponse, marketDataQuotesResponse, subscribeResponse ->
createDetailsModel(instrumentByIdResponse, marketDataQuotesResponse, subscribeResponse)
})
}
private fun createDetailsModel(instrumentByIdResponse: List<InstrumentByIdResponse>, marketDataQuotesResponse: MarketDataQuotesResponse, subscribeResult: SubscribeResult): DetailsModel {
return DetailsModel(instrumentByIdResponse, marketDataQuotesResponse, subscribeResult)
}
data class DetailsModel(
val instrument: List<InstrumentByIdResponse>,
val marketDataQuotes: MarketDataQuotesResponse,
val subscribe: SubscribeResult)
RemoteService :
fun requestInstrumentById(instrumentById: InstrumentById) = ApiService.requestInstrumentById(instrumentById)
APIService :
#Headers("Content-Type: application/json")
#POST("search/instrumentsbyid")
fun requestInstrumentById(#Body instrumentById: InstrumentById): Observable<BaseResponse<List<InstrumentByIdResponse>>>
API Structure
Error that i get on Zip Operator