Skip to content

Instantly share code, notes, and snippets.

View dcampogiani's full-sized avatar

Daniele Campogiani dcampogiani

View GitHub Profile
@dcampogiani
dcampogiani / gist:45043dc7938b2fa4f4bcc065fb7edffc
Created February 25, 2022 10:10
Flow and RecyclerView extensions
/**
* This method requires a LinearLayoutManager
*/
val RecyclerView.visibleFlow: Flow<List<Int>>
get() = callbackFlow<List<Int>> {
val scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dx == 0 && dy == 0) {
private fun bindCardDetails(card: CardDetails) {
owner.text = card.owner
number.text = card.number
date.text = "${card.expirationMonth}/${card.expirationYear}"
}
private fun bindUseCases(cameraProvider: ProcessCameraProvider) {
val preview = buildPreview()
val takePicture = buildTakePicture()
val cameraSelector = buildCameraSelector()
cameraProvider.bindToLifecycle(this, cameraSelector, preview, takePicture)
button.setOnClickListener {
lifecycle.coroutineScope.launchWhenResumed {
val imageProxy = takePicture.takePicture(executor)
private val useCase = ExtractDataUseCase(TextRecognition.getClient())
private fun extractExpiration(lines: List<String>): Pair<String?, String?> {
val expirationLine = extractExpirationLine(lines)
val month = expirationLine?.substring(startIndex = 0, endIndex = 2)
val year = expirationLine?.substring(startIndex = 3)
return Pair(month, year)
}
private fun extractExpirationLine(lines: List<String>) =
lines.flatMap { it.split(" ") }
.firstOrNull { (it.length == 5 || it.length == 7) && it[2] == '/' }
private fun extractNumber(lines: List<String>): String? {
return lines.firstOrNull { line ->
val subNumbers = line.split(" ")
subNumbers.isNotEmpty() && subNumbers.flatMap { it.asIterable() }.all { it.isDigit() }
}
}
private fun extractOwner(lines: List<String>): String? {
return lines
.filter { it.contains(" ") }
.filter { line -> line.asIterable().none { char -> char.isDigit() } }
.maxBy { it.length }
}
object Extractor {
fun extractData(input: String): CardDetails {
val lines = input.split("\n")
val owner = extractOwner(lines)
val number = extractNumber(lines)
val (month, year) = extractExpiration(lines)
return CardDetails(
owner = owner,
number = number,
data class CardDetails(
val owner: String?,
val number: String?,
val expirationMonth: String?,
val expirationYear: String?
)