Skip to content

Instantly share code, notes, and snippets.

View manoamaro's full-sized avatar

Manoel Amaro manoamaro

View GitHub Profile
import SwiftUI
import UIKit
struct DataImageView<Placeholder: View>: View {
private final class ViewModel: ObservableObject {
@Published var image: UIImage?
private let data: Data
fun getEventsFlow(): Flow<Event> = flow {
coroutineScope { // Wrap the code with this, to have access to the coroutine scope
val url = "https://hacker-news.firebaseio.com/v0/updates.json"
// Gets HttpURLConnection. Blocking function. Should run in background
val conn = (URL(url).openConnection() as HttpURLConnection).also {
it.setRequestProperty("Accept", "text/event-stream") // set this Header to stream
it.doInput = true // enable inputStream
}
data class Event(val name: String = "", val data: String = "")
fun getEventsFlow(): Flow<Event> = flow {
val url = "https://hacker-news.firebaseio.com/v0/updates.json"
// Gets HttpURLConnection. Blocking function. Should run in background
val conn = (URL(url).openConnection() as HttpURLConnection).also {
it.setRequestProperty("Accept", "text/event-stream") // set this Header to stream
it.doInput = true // enable inputStream
}
@manoamaro
manoamaro / kt-coroutines-flow-01.kt
Created April 5, 2020 13:19
kt-coroutines-flow-01
fun randomIntFlow(): Flow<Int> = flow { //flow builder
// suspend functions can be called from inside the flow
for (i in 1..10) {
emit(Random.nextInt()) // emit the value
delay(1000) //suspend function
}
}
runBlocking {
randomIntFlow().collect { i -> println(i) } // collect() is a suspend function.
// Using the GlobalScope just as an example.
// For Android, should use the lifecycle scope so everything is stopped according to the lifecycle
GlobalScope.launch(Dispatchers.Main) { // Where the non-blocking code will run - Main Thread
// "synchronous" call. All following code will run only when this blocks finish and return.
val result1 = withContext(Dispatchers.IO) {// where this code will run - IO specific pool of threads
// background thread
// blocking or cpu intensive work
// can return something
@manoamaro
manoamaro / sudoku-solver-bt.rb
Created June 2, 2013 19:15
Sudoku solver by backtracking algorithm
require 'matrix'
class Matrix
# Assign the given value to the slot at the specified row and column
def []=(row, column, value)
@rows[row][column] = value
end
def to_s
[sprintf("%d x %d Matrix", @rows.length, column_size),
@rows.map { |row| row.inspect }].flatten.join("\n")
@manoamaro
manoamaro / gist:3000167
Created June 26, 2012 23:36
Bellman-Ford algorithm
class Vertice
attr_accessor :predecessor, :d, :name
def initialize(n)
@name = n
end
end
class Edge
attr_accessor :source, :destination, :w
def initialize(s,d,w)