Skip to content

change the signature of methods to accept class object #1

@lambdaR

Description

@lambdaR

@cyb3rko hi ... can we do this in kotlin? I have changed the signature of call method to accept HelloworldCallRequest instead of String

package com.m3o.m3okotlin.services

import com.m3o.m3okotlin.M3O.getUrl
import com.m3o.m3okotlin.M3O.ktorHttpClient
import com.m3o.m3okotlin.WebSocket

import io.ktor.client.request.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

private const val SERVICE = "helloworld"

object HelloworldService {
    suspend fun call(req: HelloworldCallRequest): HelloworldCallResponse {
        return ktorHttpClient.post(getUrl(SERVICE, "Call")) {
          body = req
        }
    }
    fun stream(req: HelloworldStreamRequest, action: (Exception?, HelloworldStreamResponse?) -> Unit) {
        val url = getUrl(SERVICE, "Stream", true)
        WebSocket(url, Json.encodeToString(req)) { e, response ->
            action(e, if (response != null) Json.decodeFromString(response) else null)
        }.connect()
    }
}
@Serializable
internal data class HelloworldCallRequest(val name: String)
@Serializable
data class HelloworldCallResponse(val message: String)
@Serializable
internal data class HelloworldStreamRequest(val messages: Long, val name: String)
@Serializable
data class HelloworldStreamResponse(val message: String)

and then use it like this

package examples.helloworld.call

import com.m3o.m3okotlin.M3O
import com.m3o.m3okotlin.services.HelloWorldService

suspend fun main() {
    M3O.initialize("M3O_API_TOKEN")

    req = HelloWorldServiceRequest(name = "Jone")
    
    try {
        val response = HelloWorldService.call(req)
        println(response)
    } catch (e: Exception) {
        println(e)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions