flatMap implementation