Coroutines and suspend functions
Operations that open a user interface or perform file, recognition, or export work are exposed as Kotlin suspend functions. Call them from a coroutine.
Use a ViewModel
We recommend calling the SDK from a ViewModel and launching the coroutine in its viewModelScope:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.docutain.sdk.kmp.DocutainException
import de.docutain.sdk.kmp.DocutainSdk
import kotlinx.coroutines.launch
class ScanViewModel : ViewModel() {
var completed by mutableStateOf(false)
private set
fun scan() {
viewModelScope.launch {
try {
completed = DocutainSdk.scanDocument()
// Handle the result.
} catch (exception: DocutainException) {
// Handle the error.
}
}
}
}
In your composable, get the ViewModel and call its function:
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun ScanScreen(viewModel: ScanViewModel = viewModel { ScanViewModel() }) {
Button(onClick = { viewModel.scan() }) {
Text("Scan document")
}
}
A ViewModel outlives the Android activity. If Android recreates the activity while the scanner or Photo Payment is open, e.g. after a rotation or a font size change, the call keeps running in the viewModelScope and its result still arrives. A scope from the UI, e.g. rememberCoroutineScope(), is cancelled together with the activity and the result is lost.
The code examples in this documentation call viewModelScope.launch and assume that they run inside a ViewModel like the one above.
If your project doesn't use the multiplatform ViewModel yet, add it to the commonMain source set:
kotlin {
sourceSets {
commonMain.dependencies {
implementation("org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
}
}
}
For a complete example, see the Kotlin Multiplatform Photo Payment sample.
Threading
The KMP SDK handles the native thread dispatching required by its blocking operations. Do not use runBlocking on the UI thread.
The following common API methods suspend:
scanDocumentloadFileandaddPagegetTextandgetTextPagesetAnalyzeConfigurationandanalyzewritePDF,writeImage, andgetImageBytesstartPhotoPaymentandstartPhotoPaymentWithExternalFiles