Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kotlin: Use Coroutines #1597

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Do not tap into the executors or Handlers
Bad practice, we can use kotlin coroutines instead.
Doomsdayrs committed Jun 19, 2024
commit 06bd5ca624b4bea03fb132e4e11f69c7a1b046b2
27 changes: 15 additions & 12 deletions kotlin/src/androidMain/kotlin/org/vosk/android/StorageService.kt
Original file line number Diff line number Diff line change
@@ -18,13 +18,13 @@ package org.vosk.android
import android.content.Context
import android.content.res.AssetManager
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.vosk.Model
import org.vosk.exception.IOException
import java.io.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import java.util.function.Consumer

/**
@@ -34,6 +34,7 @@ import java.util.function.Consumer
object StorageService {
private val TAG = StorageService::class.simpleName

@Deprecated("Use your own multi-threading. Or maybe just use Kotlin Coroutines.")
@JvmStatic
fun unpack(
context: Context,
@@ -42,20 +43,22 @@ object StorageService {
completeCallback: Consumer<Model>,
errorCallback: Consumer<IOException>
) {
val executor: Executor =
Executors.newSingleThreadExecutor() // change according to your requirements
val handler = Handler(Looper.getMainLooper())
executor.execute {
GlobalScope.launch(Dispatchers.IO) {
try {
val outputPath = sync(context, sourcePath, targetPath)
val model = Model(outputPath)
handler.post { completeCallback.accept(model) }
val model = unpack(context, sourcePath, targetPath)
launch(Dispatchers.Main) { completeCallback.accept(model) }
} catch (e: IOException) {
handler.post { errorCallback.accept(e) }
launch(Dispatchers.Main) { errorCallback.accept(e) }
}
}
}

@Throws(IOException::class)
fun unpack(context: Context, sourcePath: String, targetPath: String): Model {
val outputPath = sync(context, sourcePath, targetPath)
return Model(outputPath)
}

@JvmStatic
@Throws(IOException::class)
fun sync(context: Context, sourcePath: String, targetPath: String): String {