ref: 04d9b254197db70e7500b745061c9b0818405b21
app/src/main/java/ml/adamsprogs/bimba/dashboard/ui/home/HomeViewModel.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package ml.adamsprogs.bimba.dashboard.ui.home import android.content.Context import android.net.ConnectivityManager import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import ml.adamsprogs.bimba.api.* import java.io.InputStream class HomeViewModel : ViewModel() { private val mutableItems = MutableLiveData<List<Item>>() val items: LiveData<List<Item>> = mutableItems fun getItems(cm: ConnectivityManager, server: Server, query: String) { viewModelScope.launch { val itemsResult = queryItems(cm, server, query, limit = 6) if (itemsResult.error != null) { Log.e("HVM.getItems", "$itemsResult") } else { val response = unmarshallItemResponse(itemsResult.stream!!) mutableItems.value = (response as ItemsSuccess).items } } } private suspend fun unmarshallItemResponse(stream: InputStream): ItemsResponse { return withContext(Dispatchers.IO) { ItemsResponse.unmarshal(stream) } } inner class SearchBarWatcher( private val context: Context, private val cm: ConnectivityManager ) : TextWatcher { private val handler = Handler(Looper.getMainLooper()) private var workRunnable = Runnable {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { handler.removeCallbacks(workRunnable) workRunnable = Runnable { val text = s.toString() getItems( cm, Server.get(context), text ) } handler.postDelayed( workRunnable, 750 ) // todo(ux,low) make good time (probably between 500, 1000ms) } } } |