Bimba.git

ref: 0f3ae9e13096218a22641ba4684cd48d77f987e3

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
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(server: Server, query: String) {
		viewModelScope.launch {
			val itemsStream = queryItems(server, query)
			if (itemsStream == null) {
				// todo Toast.makeText(context, "Couldn't get response", Toast.LENGTH_SHORT).show()
			} else {
				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")
				}
			}
		}
	}
}