Bimba.git

ref: 62e0c1d69f4e7d1d4557870d82cf5fc18af85534

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
package ml.adamsprogs.bimba.dashboard.ui.home

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(query: String) {
		viewModelScope.launch {
			val itemsStream = queryItems(query)
			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")
				}
			}
		}
	}

	private fun String.printable() = map {
		when (Character.getType(it).toByte()) {
			Character.CONTROL, Character.FORMAT, Character.PRIVATE_USE,
			Character.SURROGATE, Character.UNASSIGNED, Character.OTHER_SYMBOL
			-> "\\u%04x".format(it.code)
			else -> it.toString()
		}
	}.joinToString("")
}