Creating an actor to use as a counter

The next step will be to create an actor that will encapsulate the counter with the amount of news that has been found for the given search. Because this actor can be accessed from many areas, we will write it to be a singleton.

Let's create the Kotlin file ResultsCounter.kt in the package co.starcarr.rssreader.search and then create the singleton ResultsCounter inside it with a couple of properties:

object ResultsCounter {
private val context = newSingleThreadContext("counter")
private var counter = 0
}

First we have context, which is a CoroutineContext that consists of a single thread. The coroutine of the actor will ultimately run with that context, so we will avoid atomicity violations by having all the increments run confined there. Let's now add the actor as a private property:

private val actor = actor<Void?>(context) {
for (msg in channel) {
counter++
}
}

Similar to our examples before, this implementation will initially be a coroutine increasing the counter. But we have made it private so that we can offer a method in ResultsCounter for the clients of this API to increase it easily. Let's add this function now:

suspend fun increment() = actor.send(null)

This function can be called from any coroutine, and will keep the API clean and the implementation encapsulated. If tomorrow we decide to change to a mutex, we could still implement it without having to break the API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.104.124