Send updates from Kotlin multiplatform library to the app that is using the library

Hello
Please I need to send update from my multiplatform library to the app that is using the library, I need the updates to be fired every 1 minute

So I can not find the correct way to do that
Can you help me please ?

What do you mean by “send updates”?

1 Like

I mean for example I have a news server
I need my library to have a timer to call the news server every 1 minute
And if there are new news will inform the application that is using the library, means sending updates to that app

There are several ways to do it. Classic approach would be that the application registers a callback in the library, so the library could send notifications using this callback.

Recently, we prefer reactive programming for things like this. It is more complicated and harder to learn, but much more powerful and less error-prone. In Kotlin this is represented by flows. Below is an example, but note it is only an example. Implementation really depends on your specific needs.

suspend fun main() {
    val newsService = NewsService(GlobalScope)

    newsService.newsFlow.collect { println(it) }
}

class NewsService(
    private val coroutine: CoroutineScope
) {
    val newsFlow = flow {
        while (true) {
            acquireNewItems().forEach { emit(it) }
            delay(Duration.ofMinutes(1))
        }
    }.shareIn(coroutine, SharingStarted.Lazily)

    private fun acquireNewItems(): List<News> = TODO()
}

Also, if you are targeting Android then I believe some of its APIs are already based on flows and/or provide adapters to for example LiveData or things related to Compose.

@broot
Thanks a lot for your answer it is really very helpful

Hi @broot

Please can I have an example about how to do this or if there is a tutorial for that please

“There are several ways to do it. Classic approach would be that the application registers a callback in the library, so the library could send notifications using this callback.”

Read about the Observer pattern.