Bimba.git

ref: 6f38b586f615a021d17d794b1517d692eedb5be7

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
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")
				}
			}
		}
	}
}