I was reading Android CameraX codelab: https://codelabs.developers.google.com/codelabs/camerax-getting-started#4
The simplified code snippet is like this:
class MainActivity : AppCompatActivity() {
private var imageCapture: ImageCapture? = null
//(some other codes here...)
private fun takePhoto() {
// Get a stable reference of the modifiable image capture use case
val imageCapture = imageCapture ?: return
//(some other codes here...)
}
}
In the codelab, it says:
First, get a reference to the ImageCapture use case.
Why do we need a new reference imageCapture
in takePhoto()
?
Can't we just use the imageCapture
in MainActivity
?
Is this for some kind of 'best practice' stuff or am I missing something?
Any advice would be greatly appreciated!
Its equivalent to a null check .
stable reference -> Not null reference
its similar to
if(imageCapture==null) return;
Also in the code lab they have mentioned the same thing.
First, get a reference to the ImageCapture use case. If the use case is null, exit out of the function. This will be null If you tap the photo button before image capture is set up. Without the return statement, the app would crash if it was null.
So basically you are removing the possibility of an NPE which can done in multiple ways and they happen to use a Another local variable for it . it can also be done with let
.
imageCapture?.let{
// code goes here
}