Skip to content

Commit

Permalink
Check, LiveData extended
Browse files Browse the repository at this point in the history
  • Loading branch information
Pluu committed Oct 15, 2023
1 parent b8c4f2f commit 9733952
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions lint/src/main/java/com/pluu/lint/LiveDataObserveNotNullDetector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.isKotlin
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.uast.UCallExpression
Expand All @@ -25,6 +26,8 @@ class LiveDataObserveNotNullDetector : Detector(), SourceCodeScanner {
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
super.visitMethodCall(context, node, method)
if (!isKotlin(context.psiFile)) return
if (!isLiveDataReceiver(context, node)) return

val lambda = node.valueArguments.firstIsInstanceOrNull<ULambdaExpression>()
?.valueParameters ?: return
if (lambda.size != 1) return
Expand All @@ -34,6 +37,15 @@ class LiveDataObserveNotNullDetector : Detector(), SourceCodeScanner {
}
}

private fun isLiveDataReceiver(context: JavaContext, node: UCallExpression): Boolean {
val psiClassType = (node.receiver?.getExpressionType() as? PsiClassType) ?: return false
return context.evaluator.extendsClass(
psiClassType.rawType().resolve(),
"androidx.lifecycle.LiveData",
false
)
}

private fun report(context: JavaContext, node: UCallExpression) {
// Lint 7.0 이상부터 사용
val incident = Incident(context, ISSUE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import com.pluu.lintstudy.BaseActivity
import com.pluu.lintstudy.utils.observeNotNull
class SampleActivity : BaseActivity() {
private val stringLiveData: LiveData<String> = MutableLiveData<String>()
private val stringLiveData: LiveData<String?> = MutableLiveData<String?>()
private val stringNullableLiveData: LiveData<String?> = MutableLiveData<String?>()
private val unitLiveData: LiveData<Unit> = MutableLiveData<Unit>()
Expand Down

0 comments on commit 9733952

Please sign in to comment.