:thread: How can I add import for `"kotlinx.corout...
# squarelibraries
r
🧵 How can I add import for
"kotlinx.coroutines.flow.mapNotNull"
using kotlin poet? I tried the below it does not add import for the extension function
Copy code
FileSpec.builder(packageName, factoryClassName)
                .addImport("kotlinx.coroutines.flow", "mapNotNull")
h
Use a MemberName with isExtension=true and %M. That will add the import automatically.
You should rarely need to use addImport at all
r
I am adding the code like this using kotlin poet
Copy code
funBuilder.addStatement("""
                            return connectionManager
                                .rawMessageFlow
                                .mapNotNull { rawJson ->
                                    runCatching { messageAdapter.fromJson(rawJson, $messageType::class.java) }
                                        .onFailure {
                                            // Log exception
                                        }
                                        .getOrNull()
                                }
                        """.trimIndent())
how can I use MemberName here?
h
Instead of .mapNotNull use %M and add the MemberName as a arg parameter
👍 1
And use %T instead of $messageType.
r
how can I pass the lambda as an argument with %M
Copy code
.mapNotNull { rawJson ->
                                    runCatching { messageAdapter.fromJson(rawJson, $messageType::class.java) }
                                        .onFailure {
                                            // Log exception
                                        }
                                        .getOrNull()
                                }
c
Copy code
.%M { rawJson ->
                                    runCatching { messageAdapter.fromJson(rawJson, $messageType::class.java) }
basically its just an ‘intelligent’ string format argument.
r
oh it can support lambda as well I see I thought I need to pass it in parenthesis only it makese sense now
h
I have no idea what you mean with lambda but either use it this way:
Copy code
funBuilder.addStatement(
    """return connectionManager
                .rawMessageFlow
                .%M { rawJson ->
                   runCatching { messageAdapter.fromJson(rawJson, %T::class.java) }
                     .onFailure {
                        // Log exception
                     }
                     .getOrNull()
                }
    """.trimIndent(),
    MemberName("kotlinx.coroutines.flow", "mapNotNull", isExtension = true),
    ClassName("my-package", messageType),
  )
Or refactor the code and use
beginControlFlow
etc. to minify the String but that's a little bit over-engineered.