Skip to content

Kotlin examples

Small pieces of an app built on com.audiencekit:audiencekit, one per thing a screen does. They have no UI of their own, so the same code feeds a Compose screen, a RecyclerView or a server, and the SDK’s tests compile and run every one against a stub API (ExamplesTest).

File What it shows
WhatsOn.kt A locale’s upcoming events grouped by night, in the locale’s time zone, for a list or a widget
NewsDigest.kt A Markdown digest of a locale’s news and its national news
MemberActions.kt What a signed-in member does: RSVP, calendar links, the door pass and reporting

Signing in, the session and the Android client are in the SDK’s README.

WhatsOn.kt
// The "What's on" screen: a locale's upcoming events grouped by night, the way a list or a widget shows them. The
// models are plain data, so the same function feeds a Compose LazyColumn, a RecyclerView or a server-rendered page.
package com.audiencekit.examples
import com.audiencekit.AudienceKitClient
import com.audiencekit.Event
import com.audiencekit.EventWindow
import com.audiencekit.events
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
/** One night's events, soonest first. */
data class Night(val date: LocalDate, val title: String, val events: List<Row>)
/** What a row shows: the event, where, and when, in the locale's time zone. */
data class Row(val id: String, val name: String, val where: String?, val time: String, val canceled: Boolean)
private val dayTitle = DateTimeFormatter.ofPattern("EEEE, MMMM d", Locale.US)
private val timeOfDay = DateTimeFormatter.ofPattern("h:mm a", Locale.US)
/** Groups [events] by the night they start on in [zone]; events with no start yet are left out. */
fun nights(events: List<Event>, zone: ZoneId): List<Night> =
events
.mapNotNull { event -> event.startAt?.let { event to Instant.parse(it).atZone(zone) } }
.sortedBy { (_, start) -> start }
.groupBy({ (_, start) -> start.toLocalDate() }) { (event, start) ->
Row(event.id, event.name ?: "Untitled", event.venueName, timeOfDay.format(start), event.isCanceled)
}
.toSortedMap()
.map { (date, rows) -> Night(date, dayTitle.format(date), rows) }
/** The locale's upcoming events, by night. */
suspend fun whatsOn(client: AudienceKitClient, localeId: String, zone: ZoneId = ZoneId.of("America/Denver")): List<Night> =
nights(client.events(window = EventWindow.UPCOMING, localeId = localeId), zone)
NewsDigest.kt
// A Markdown digest of a locale's news, for a newsletter, a Discord post or a "This week" card in the app. Empty for
// an audience without Soapbox, rather than failing.
package com.audiencekit.examples
import com.audiencekit.Article
import com.audiencekit.AudienceKitClient
import com.audiencekit.articles
import com.audiencekit.nationalArticles
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
/** One article as a Markdown list item. A teaser carries only the start: the rest is on the publication's site. */
fun line(article: Article): String = buildString {
val name = article.publication.name
append("- **${article.title}**, ${article.byline} for $name")
if (article.teaser && article.canonicalUrl != null) append(" ([read on $name](https://github.com/lwm-luminx/audience-kit-sdk/blob/main/android/examples/${article.canonicalUrl}))")
article.summary?.let { append("\n $it") }
article.disclosure?.let { append("\n _${it}_") }
}
/** The digest for the locale named [localeName] (or the audience's first): its news, then the national news. */
suspend fun digest(client: AudienceKitClient, localeName: String? = null): String = coroutineScope {
val locales = client.locales()
val locale = locales.firstOrNull { it.name == localeName } ?: locales.firstOrNull() ?: return@coroutineScope ""
val local = async { client.articles(localeId = locale.id, first = 10) }
val national = async { client.nationalArticles(localeId = locale.id, first = 5) }
val sections = mutableListOf("# ${locale.name ?: "Your city"} this week")
val news = local.await()
if (news.isNotEmpty()) sections += "## Local news\n\n" + news.joinToString("\n", transform = ::line)
val seen = news.map { it.id }.toSet()
val elsewhere = national.await().filter { it.id !in seen }
if (elsewhere.isNotEmpty()) sections += "## Around the country\n\n" + elsewhere.joinToString("\n", transform = ::line)
if (sections.size > 1) sections.joinToString("\n\n") + "\n" else ""
}
MemberActions.kt
// What a signed-in member does in the app, in the order a night out goes: RSVP, add it to their calendar, show the
// cover pass at the door, and report something they saw in chat.
package com.audiencekit.examples
import com.audiencekit.AdmissionStatus
import com.audiencekit.AudienceKitClient
import com.audiencekit.CoverPass
import com.audiencekit.RSVPState
import com.audiencekit.ReportCopy
import com.audiencekit.ReportResult
import com.audiencekit.ReportTarget
import com.audiencekit.createCalendarFeed
import com.audiencekit.followVenueInCalendar
import com.audiencekit.reportContent
/** Says they're going, and returns how many are going now. */
suspend fun goingTo(client: AudienceKitClient, eventId: String): Int = client.rsvp(eventId, RSVPState.ATTENDING).count
/** Links that add every event they're going to (and every event at [venueId]) to their own calendar. */
suspend fun calendarLinks(client: AudienceKitClient, venueId: String? = null): Map<String, String> {
val feed = if (venueId != null) client.followVenueInCalendar(venueId) else client.createCalendarFeed()
return mapOf("appleOrOutlook" to feed.links.webcalUrl, "google" to feed.links.googleUrl)
}
/** The door code and how many seconds it's good for. */
data class DoorPass(val code: String, val refreshInSeconds: Long)
/**
* The code to show at the door for tonight's cover at a venue. It changes every 30 seconds, so draw it as a QR code
* and draw it again when [DoorPass.refreshInSeconds] runs out. It's made on the phone, so it works with no signal.
*/
suspend fun doorPass(client: AudienceKitClient, venueId: String, now: Long = System.currentTimeMillis() / 1000): DoorPass? {
val pass = client.venueCover(venueId)?.viewerAdmission ?: return null
val secret = pass.passSecret ?: return null
if (pass.status != AdmissionStatus.PAID) return null
return DoorPass(CoverPass.code(pass.id, secret, now), CoverPass.secondsUntilNextWindow(now))
}
/** Reports a chat message as harassment and blocks whoever sent it. */
suspend fun reportHarassment(client: AudienceKitClient, messageId: String): ReportResult =
client.reportContent(ReportTarget.MESSAGE, messageId, reason = ReportCopy.REASONS[1], block = true)