Useful Lambda expressions to communicate with & between Fragments or Dialogs in Android

Lukoh Nam
빅펄 (헤드라잇)
2 min readFeb 20, 2022

We often need to have channels of communication between Fragments and its Fragments or between two or more Fragments or Dialogs to properly react to user events, or to share state information or value. Two or more fragments or dialogs in the same activity often need to communicate with each other or pass the value. There are many useful ways to communicate between Fragments or Dialogs such as using those methods like below link : https://developer.android.com/guide/fragments/communicate

Now I’d like to introduce the other way to communicate with Fragment or Dialog with value using Lambda expression.

Please refer to below code:

class Category1NewsFragment : BaseNewsFragment<FragmentCategoryNewsBinding>(CATEGORY_1_NEWS) {
...
...
containerCommentCount.setSafeOnClickListener {
CommentReplyDialog(
articleActivity,
userId,
item,
position,
{ articleId, commentReportSchema ->
removeComment(tvComment, position)
onCommentReported(articleId, commentReportSchema)
},
{ userId, blockedUserId ->
removeComment(tvComment, position)
onUserBlocked(userId, blockedUserId)
},
{ updated, articleId, count ->
onCommentReplyUpdated(updated, articleId, count)
}).show(
articleActivity.supportFragmentManager,
"BottomSheetReportDialog"
)
...
...
}class CommentReplyDialog(
private val articleActivity: ArticleActivity,
private val userId: String,
private val comment: Comment,
private val position: Int,
val inline onReportComment: (articleId: String,
commentReportSchema: CommentReportSchema) -> Unit,
val inline onBlockUser: (userId: String, blockUserId: String) ->
Unit,
val inline onUpdateCommentReply: (updated: Boolean, articleId:
String, count: Int) -> Unit
) : BottomSheetDialogFragment(), Injectable {
...
...
containerReport.setSafeOnClickListener {
CommentReportDialog(
userId, comment, {
onReportComment(
comment.article_id,
CommentReportSchema(
comment.content,
comment.user_id)
)
dismiss()
}, { userId, blockedUserId ->
onBlockUser(userId, blockedUserId)
dismiss()
}).show(
articleActivity.supportFragmentManager,
"BottomSheetReportDialog"
)
}
...
...
}

Now we can pass values between two Fragments or between a Fragment and Dialog using Lambda expression like above code.

This method would be very useful and easy for passing values rather than methods like ViewModel or other method sometimes and we can implement the same behavior with less code implementation than other methods.

I recommend this way if we want to instantly update the UI with values or data from another Fragment or Dialog.

Please read the below article if you want to get more:

https://kotlinlang.org/docs/lambdas.html#lambda-expressions-and-anonymous-functions

--

--