ref: 6bc2a8f60649a48d070b11c662d228322388bf18
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 72 73 |
package ml.adamsprogs.bimba.dashboard.ui.home import android.content.SharedPreferences import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher 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(server: Server, query: String) { viewModelScope.launch { val itemsStream = queryItems(server, query, limit = 6) if (itemsStream != null) { mutableItems.value = unmarshallItemResponse(itemsStream) } } } private suspend fun unmarshallItemResponse(stream: InputStream): List<Item> { return withContext(Dispatchers.IO) { when (val response = ItemsResponse.unmarshall(stream)) { is ItemsSuccess -> { return@withContext response.items } else -> { TODO("Error response") } } } } inner class SearchBarWatcher(private val preferences: SharedPreferences) : 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 host = preferences.getString("host", "bimba.apiote.xyz")!! val text = s.toString() getItems( Server( host, preferences.getString("token", "")!!, preferences.getString("${host}_feeds", "")!! ), text ) } handler.postDelayed( workRunnable, 1000 ) // todo(ux,low) make good time (probably between 500, 1000ms) } } } |