Hello everyone. Please, is there a better way to d...
# codereview
g
Hello everyone. Please, is there a better way to do this?
Copy code
private val eventsCache: MutableSet<TextNoteEvent> = mutableSetOf()         private val profiles: MutableSet<MetadataEvent> = mutableSetOf()
private val postCache: MutableSet<Post> = mutableSetOf()                                                                                   val eventsByPubkey = eventsCache
    .distinctBy { it.id.toHex() }
    .associateBy { it.pubKey.toHex() }

val posts = profiles
    //.filter { eventsByPubkey[it.pubKey.toHex()] != null }
    .map { metadataEvent ->
        val textEvent = eventsByPubkey[metadataEvent.pubKey.toHex()]
        if (textEvent != null){
            if (textEvent.pubKey.toHex() == metadataEvent.pubKey.toHex()){
                val post = Post(
                    user = User(
                        username = metadataEvent
                            .contactMetaData.name ?: textEvent.pubKey.toNpub().take(9),
                        pubKey = textEvent.pubKey.toHex(),
                        bio = metadataEvent.contactMetaData.about ?: "",
                        image = metadataEvent.contactMetaData.picture ?: ""
                    ),
                    postId = textEvent.id.toHex(),
                    timestamp = textEvent.createdAt,
                    textContent = textEvent.content,
                    imageLinks = textEvent.content.urlsInText()
                )
                postCache.add(post)
            } else {
                val post = Post(
                    user = User(
                        username = textEvent.pubKey.toNpub().take(9),
                        pubKey = textEvent.pubKey.toHex(),
                        bio = metadataEvent.contactMetaData.about ?: "",
                        image = metadataEvent.contactMetaData.picture ?: ""
                    ),
                    postId = textEvent.id.toHex(),
                    timestamp = textEvent.createdAt,
                    textContent = textEvent.content,
                    imageLinks = textEvent.content.urlsInText()
                )
                postCache.add(post)
            }

        }
    }
p
because
if
is an expression in Kotlin, you can put the only condition logic directly inline in the assignment
g
Thanks @Paul Griffith.
My goal was to do something in the style of Flow's combine, for two collections.
p
(I also use
mapNotNullTo
to make the collection to the final output more explicit without the ’cache` variable)
g
Unfortunately, zip does not work well for me.
I see. I was looking for something like mapNotNullTo, but due to my limited knowledge, could not find it.